1

I'm fairly new to evaluating algorithm complexity and my task is to measure real runtime for a few functions.

I have been using time.process_time(). Is this the best way to go about it?

  • Is it accurate?
  • Will runtime vary based on how "busy" my laptop is? (ex. I have other apps open)
  • Are there other better methods?
  • 1
    Use the [timeit](https://docs.python.org/3.8/library/timeit.html) module – Barmar Aug 24 '20 at 20:13
  • Does this answer your question? [How to use timeit when timing a function](https://stackoverflow.com/questions/19010793/how-to-use-timeit-when-timing-a-function) – Julia Aug 24 '20 at 20:15

1 Answers1

3

Option 1: Profiling Code to Learn about Overall Performance in Real-Life Scenarios

This a great way of determining the impact of running your functions in real-life scenarios.

To learn more about your code performance, you can use Profiling.

Run the following command to evaluate function performance:

import cProfile
cProfile.run('function()')

This gives you valuable information such as; Total call count, cumulative time, times for each function call, and call count for each function.

Option 2: Investigating Spesific Function Call Duration

This is a great method to learn about function runtime duration.

Using decorator:

from functools import wraps
from time import time

def timing(f):
    @wraps(f)
    def wrap(*args, **kw):
        ts = time()
        result = f(*args, **kw)
        te = time()
        print 'func:%r args:[%r, %r] took: %2.4f sec' % \
          (f.__name__, args, kw, te-ts)
        return result
    return wrap

Use it like this:

@timing
def function():
    <code>
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22