Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get time of execution of a block of code in Python 2.7

I would like to measure the time elapsed to evaluate a block of code in a Python program, possibly separating between user cpu time, system cpu time and elapsed time.

I know the timeit module, but I have many self-written functions and it is not very easy to pass them in the setup process.

I would rather have something that could be used like:

#up to here I have done something.... start_counting() #or whatever command used to mark that I want to measure                    #the time elapsed in the next rows # code I want to evaluate user,system,elapsed = stop_counting() #or whatever command says:                                       #stop the timer and return the times 

The user and system CPU times are not essential (though I would like to measure them), but for the elapsed time I would like to be able to do something like this, rather than using complicated commands or modules.

like image 249
lucacerone Avatar asked Mar 29 '13 16:03

lucacerone


People also ask

How do I tell how long a Python script is running?

Finding the Execution Time using Python time Module. The first method to find the execution time of a Python script is via the time() method of the time module. Basically, you need to call the time() method before the code starts. The time() method of the time module returns the current system time.

What does %% time mean in Python?

%%time is a magic command. It's a part of IPython. %%time prints the wall time for the entire cell whereas %time gives you the time for first line only. Using %%time or %time prints 2 values: CPU Times.


2 Answers

To get the elapsed time in seconds, you can use timeit.default_timer():

import timeit start_time = timeit.default_timer() # code you want to evaluate elapsed = timeit.default_timer() - start_time 

timeit.default_timer() is used instead of time.time() or time.clock() because it will choose the timing function that has the higher resolution for any platform.

like image 178
Andrew Clark Avatar answered Sep 30 '22 14:09

Andrew Clark


I always use a decorator to do some extra work for a existing function, including to get the execution time. It is pythonic and simple.

import time  def time_usage(func):     def wrapper(*args, **kwargs):         beg_ts = time.time()         retval = func(*args, **kwargs)         end_ts = time.time()         print("elapsed time: %f" % (end_ts - beg_ts))         return retval     return wrapper  @time_usage def test():     for i in xrange(0, 10000):         pass  if __name__ == "__main__":     test() 
like image 25
Yarkee Avatar answered Sep 30 '22 13:09

Yarkee