Is there any way to configure the python command which will return the runtime of a code? E.g., py - <some argument> test.py
will return test.py took 37 nanoseconds to run
? I am on Windows11 using Python 3.10.
P.S. > I want to avoid time.time()
unless that's the only solution.
Thanks in advance.
** Solution**
Basis the comments, I tried measure-command {py test.py}
in the command prompt. I did the job.
Thank you all.
CodePudding user response:
Basis the comments, I tried measure-command {py test.py}
in the Windows PowerShell command prompt. It did the job.
Output:
Days : 0
Hours : 0
Minutes : 0
Seconds : 2
Milliseconds : 891
Ticks : 28910749
TotalDays : 3.34615150462963E-05
TotalHours : 0.000803076361111111
TotalMinutes : 0.0481845816666667
TotalSeconds : 2.8910749
TotalMilliseconds : 2891.0749
Thank you all.
CodePudding user response:
You could use cProfile
for this:
python -m cProfile test.py
But it is generally better to use an external program for this, since profilers like cProfile
have significant overhead.
Which external program to use depends on the operating system.
- ms-windows:
measure-command
- POSIX operating systems:
time
However, if you need to improve the speed of a Python program, cProfile
is the tool of choice. It provides detailed insight in where your program is spending its time.
For testing small snippets of code, timeit
is useful:
python3 -m timeit '"-".join(str(n) for n in range(100))'
20000 loops, best of 5: 18.4 usec per loop
CodePudding user response:
Maybe cProfile
is something that suits your needs? You can the documentation here: https://docs.python.org/3/library/profile.html.
You can add this at the beginning of a main function for instance and it returns the runtime for each function. Also the cumulative times.
You can even combine this with a package like snakeviz
(https://jiffyclub.github.io/snakeviz/) to create a nice graph. That will show you immediately what are the bottlenecks of you program.
CodePudding user response:
You can try using Jupyter Notebooks. There you will see code exceution time.