There are a few ways how to measure time in python.
First, there are two useful functions for time measurement time.time
and time.clock
. time.time
returns the time in seconds since the epoch (January 1, 1970 for Unix and January 1, 1601 for Windows).
While time.time
behaves the same on Unix and on Windows, time.clock
has different meanings. On Unix, time.clock
returns the current processor time expressed in seconds, i.e., the CPU time it takes to execute the current thread so far. While on Windows, it returns the total time to execute a program in a computer expressed in seconds elapsed since the first call to this function,
import time start_time = time.time() # do your work here end_time = time.time() print(end_time - start_time)
Instead of dealing with the different behaviors of time.time()
and time.clock()
on different platforms, which is often error-prone, Python's timeit
module provides a simple way for timing.
import timeit def foo(): return map(lambda x: x^2, range(10)) print(timeit.timeit(foo))
or
import timeit a = 5 def foo(x): return x + 1 print(timeit.timeit("foo(a)"))
Second, for long running tasks
from datetime import datetime start_time = datetime.now() # do your work here end_time = datetime.now() print('Duration: {0}'.format(end_time - start_time))
Third, from terminal in Linux
time python script.py