I mainly used two ways to measure code execution time between Python scripts or parts of them.
Command line:
python3 -m timeit -n 1 -r 1 -p -u sec "import os; os.system('python3 myprogram.py')"
-m timeit
invoke timeit
module
-n 1
times you wan to execute the "statement" (== your 'python "program"/script/foo.py')
-r 1
times to repeat the timer (default 5)
-p
measure process time, not wallclock time, using internally time.process_time()
instead of time.perf_counter()
, which is the default. Very handy if your program prompts the user for input at any step, not to count, for example, the time delay introducing input.
-u sec
specify a time unit for timer output; can select nsec
, usec
, msec
, or sec
Embedded in code:
time
Python module.
As @Jeyekomon comments below the OP, time
module is a very flexible, useful, fast and simple alternative putting measurement points wherever you want. Found here How do I get time of a Python program's execution:
import time
<< put this at the beginning of your code
start_time = time.time()
<< put this in the place you want to start measuring time. Just a snapshot of instant time.
print("--- %s seconds ---" % (time.time() - start_time))
<< put this in the place you want to stop (and print) elapsed time. Just another snapshot of instant time and the subtraction respect to the previous.
Operating system alternative:
time
operating system command. Present in Windows or Linux/UNIX. But check-out for implementation particular options and flags (man time
).
Joint example using timeit
(command-line) and time
(Python module functions placed inside my code):
python3 -m timeit -n 1 -r 1 -p -u sec "import os; os.system('python3 myprogram.py')"
Tell me what term of the sequence you want to calculate: 3
(belongs to program prompt)
--- 1.0251998901367188e-05 seconds ---
<< output from embedded code (time
functions)
2
(belongs to program output)
1 loop, best of 1: 0.000448 sec per loop
<< (shell) output from timeit