Calculating computational time and memory for a code in python

Viewed 28324

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

4 Answers

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

There is a really good library called jackedCodeTimerPy for timing your code. You should then use resource package that Daniel Li suggested.

jackedCodeTimerPy gives really good reports like

label            min          max         mean        total    run count
-------  -----------  -----------  -----------  -----------  -----------
imports  0.00283813   0.00283813   0.00283813   0.00283813             1
loop     5.96046e-06  1.50204e-05  6.71864e-06  0.000335932           50

I like how it gives you statistics on it and the number of times the timer is run.

It's simple to use. If i want to measure the time code takes in a for loop i just do the following:

from jackedCodeTimerPY import JackedTiming
JTimer = JackedTiming()

for i in range(50):
  JTimer.start('loop')  # 'loop' is the name of the timer
  doSomethingHere = 'This is really useful!'
  JTimer.stop('loop')
print(JTimer.report())  # prints the timing report

You can can also have multiple timers running at the same time.

JTimer.start('first timer')
JTimer.start('second timer')
do_something = 'amazing'
JTimer.stop('first timer')

do_something = 'else'
JTimer.stop('second timer')

print(JTimer.report())  # prints the timing report

There are more use example in the repo. Hope this helps.

https://github.com/BebeSparkelSparkel/jackedCodeTimerPY

Related