Timing blocks of code - Python
Question: 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 advanced.


Answer: 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**

