Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating computational time and memory for a code in python

Tags:

python

Can some body help me as how to find how much time and how much memory does it take for a code in python?

like image 993
hafizul asad Avatar asked Aug 09 '12 15:08

hafizul asad


2 Answers

Use this for calculating time:

import time

time_start = time.clock()
#run your code
time_elapsed = (time.clock() - time_start)

As referenced by the Python documentation:

time.clock()

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Reference: http://docs.python.org/library/time.html


Use this for calculating memory:

import resource

resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

Reference: http://docs.python.org/library/resource.html

like image 102
Daniel Li Avatar answered Sep 27 '22 16:09

Daniel Li


Based on @Daniel Li's answer for cut&paste convenience and Python 3.x compatibility:

import time
import resource 

time_start = time.perf_counter()
# insert code here ...
time_elapsed = (time.perf_counter() - time_start)
memMb=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024.0/1024.0
print ("%5.1f secs %5.1f MByte" % (time_elapsed,memMb))

Example:

 2.3 secs 140.8 MByte
like image 34
Wolfgang Fahl Avatar answered Sep 27 '22 17:09

Wolfgang Fahl