Reputation: 676
In the future I'll write multiple small scripts in Python 3 which I want to time. One way would be to write every script like this:
# functions definitions go here
if __name__ == '__main__':
import time
start = time.time()
# my code
end = time.time()
print("This script took {} seconds to execute".format(end - start))
But I would have to write this into every single of these scripts. What would be the best way to time my script without including this code every single time (without losing accuracy - I'm aware of time ./script.py
)?
Upvotes: 3
Views: 82
Reputation: 104092
Use timeit vs time module. This is best for comparing one way to do something vs another way to do the same thing.
Here is a really simple template:
# if f1,f2,f3 are in another module or script, just import...
def f1(s):
# that function returns something...
def f2(s):
# etc
def f3(s):
# etc
if __name__=='__main__':
import timeit
for case, x in (('small',1000),('med',10000),('large',1000000)):
data=[some data scaled by x]
print("Case {}, {:,} x, All equal: {}".format(case,x,(f1(data)==f2(data)==f3(data))))
for f in (f1,f2,f3):
print(" {:^10s}{:.4f} secs".format(f.__name__, timeit.timeit("f(data)", setup="from __main__ import f, data", number=10)))
That should get you started. Be more specific of what issue you are having for a more specific answer.
One of my other answers has a more compete timeit
example.
You could also look at cProfile to profile a complete script and identify bottleneck functions. Then use timeit
to try variants of that bottleneck function.
Upvotes: 2
Reputation: 981
If you are on unix like environment you can use the shell.
If you are in the same folder as the script:
$ time python mymodule.py
real 0m0.307s
user 0m0.030s
sys 0m0.030s
If you have the script in a package that is installed (I recommend editable mode) you can run from anywhere using the module name
$ time python -m mypackage.mymodule
real 0m0.407s
user 0m0.033s
sys 0m0.032s
Upvotes: 0