1

I'm trying to measure the time it takes to run a block of instructions in Python, but I don't want to write things like:

start = time.clock()
...
<lines of code>
...
time_elapsed = time.clock() - start

Instead, I want to know if there is a way I can send the block of instructions as a parameter to a function that returns the elapsed time, like

time_elapsed = time_it_takes(<lines of code>)

The implementation of this method could be something like

def time_it_takes(<lines of code>):
  start = time.clock()
  result = <lines of code>
  return (result, time.clock() - start)

Does anybody know if there is some way I can do this? Thanks in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
tulians
  • 439
  • 5
  • 23

4 Answers4

7

This would be a good use of a decorator. You could write a decorator that does that like this

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)

        print('The function ran for', time.time() - start)
    return wrapper


@timer
def just_sleep():
    time.sleep(5)

just_sleep()

Output

The function ran for 5.0050904750823975

and then you can decorate any function you want to time with @timer and you can also do some other fancy things inside the decorator. Like if the function ran for more than 15 seconds do something...else do another thing

Note: This is not the most accurate way to measure execution time of a function in python

danidee
  • 9,298
  • 2
  • 35
  • 55
5

You can build your own context manager to time relatively long bits of code.

import time

class MyTimer(object):

    def __enter__(self):
        self.start = time.clock()
        return self

    def __exit__(self, typ, value, traceback):
        self.duration = time.clock() - self.start

with MyTimer() as timer:
    time.sleep(3)
print(timer.duration)

But be careful about what you are measuring. On Linux time.clock is cpu run time, but on Windows (where cpu run time is not easily available) it is a wall-clock.

Cyberwiz
  • 11,027
  • 3
  • 20
  • 40
tdelaney
  • 73,364
  • 6
  • 83
  • 116
1

If you use IPython, and it's a good thing to do, and you can construct your code to be a single line, i.e. a function call:

%timeit your-code

It's been handy for me. Hope it helps.

John Griffin
  • 377
  • 2
  • 8
0

use python -m cProfile myscript.py It provides a full log about time consumption of methods.

Amin Etesamian
  • 3,363
  • 5
  • 27
  • 50