How to use the resource module to measure the running time of a function?
Question: I want to measure the CPU running time and wall clock running time of
functions using Python code.

The resource module was suggested here: [How to measure CPU running time and
wall clock running time of a function, separately, as Python code (not from
terminal)?](http://stackoverflow.com/q/19204618/1690799)

Here is the module documentation:
<http://docs.python.org/2/library/resource.html>

The problem is that:

1) I can't figure out how to use it to measure the running time of a function.

2) I don't know how to extract that information from the object returned.

How do I do this?


Answer: Just call
[`getrusage`](http://docs.python.org/2/library/resource.html#resource.getrusage)
before and after executing the function, subtract the fields you care about,
and you're done. Since `resource` doesn't do wall time, you'll need to use a
separate function for that.

You can wrap that up in a helper function, or even a decorator, like this:

    
    
    import datetime
    import functools
    import resource
    import sys
    
    def timed(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            r0 = resource.getrusage(resource.RUSAGE_SELF)
            t0 = datetime.datetime.now()
            retval = func(*args, **kwargs)
            r = resource.getrusage(resource.RUSAGE_SELF)
            t = datetime.datetime.now()
            sys.stderr.write('{}: utime {} stime {} wall: {}\n'.format(
                func.__name__,
                datetime.timedelta(seconds=r.ru_utime-r0.ru_utime),
                datetime.timedelta(seconds=r.ru_stime-r0.ru_stime),
                t-t0))
            return retval
        return wrapper
    
    @timed
    def myfunc(i):
        for _ in range(100000000):
            pass
        return i*2
    
    print(myfunc(2))
    

This will print out something like:

    
    
    myfunc: utime 0:00:03.261688 stime 0:00:00.805324 wall 0:00:04.067109
    4
    

If you want more than a couple fields, you probably want to subtract all of
the members of the rusage results, but since these are all int or float,
that's easy:

    
    
    rdiff = resource.struct_rusage(f1-f0 for f0, f1 in zip(r0, r))
    sys.stderr.write('{}: utime {} maxrss {} nsignals {} etc.\n'.format(
        datetime.timedelta(seconds=rdiff.r_utime),
        rdiff.ru_maxrss,
        rdiff.ru_nsignals))
    

