I was wondering which time.time()
of from datetime import timedelta
was the quickest and best way to find how long a programme had been running for example.
import time
start = time.time()
#do stuff
print(start - time.time())
or (although longer)
from datetime import datetime
from datetime import timedelta
start_time = datetime.now()
def millis():
dt = datetime.now() - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
return ms
def tickscheck(start):
x = 0
count = 0
while millis() - start < 1000:
x = 4+5
#counting up
count = count + 1
print("It Took " + str(count) + " Counts\nOver " + str(millis()- start) + "ticks")
running = True
while(running == True):
tickscheck(millis())
-
\$\begingroup\$ What is your goal here — just to benchmark the Python interpreter on your machine? \$\endgroup\$200_success– 200_success2014年04月28日 20:23:36 +00:00Commented Apr 28, 2014 at 20:23
-
\$\begingroup\$ @200_success basically yes \$\endgroup\$Oliver Perring– Oliver Perring2014年04月30日 14:59:37 +00:00Commented Apr 30, 2014 at 14:59
2 Answers 2
For benchmarking process times in Python, you should probably use the timeit
module.
It is designed specifically for this purpose and you can keep your code clean by running it from the command-line.
This example is from the docs:
$ python -m timeit '"-".join(str(n) for n in range(100))'
For example, if the process you want to benchmark is a function foo
$ python -m 'timeit --setup 'from my_module import foo' 'foo()'
The snippet given with the --setup
flag sets up the environment in which you can run your test.
Check out the Python docs for more information
-
\$\begingroup\$ thnx ill look into it \$\endgroup\$Oliver Perring– Oliver Perring2014年05月03日 11:47:50 +00:00Commented May 3, 2014 at 11:47
In Python 3.3 and later you can use one of
time.perf_counter()
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
time.process_time()
Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
Older Python versions offer timeit.default_timer()
, which is now an alias of time.perf_counter()
.
The timeit
module offers tools to get more reliable timings by running the code multiple times.