1

What is the suggested way to measure function duration in python? I have seen the following:

t0 = time.time()
# do something()
duration = time.time() - t0

and

t0 = time.perf_counter()
# do something()
duration = time.perf_counter() - t0

What are the differences, and which should be used for profiling, if either?

carl.hiass
  • 1,526
  • 1
  • 6
  • 26
  • [This](https://stackoverflow.com/questions/25785243/understanding-time-perf-counter-and-time-process-time) might help. – Daniel Oct 28 '19 at 23:40

1 Answers1

1

Not your direct question, but the simplest way is to use the timeit module:

from timeit import timeit

timeit(doSomething, number=int(1e6))

It will run the test multiple times and return the total running time. Set number to a fairly high number. I usually aim for a number that causes it to run for 30-60 seconds to make sure that it runs long enough to prevent small fluctuations from effecting the results too much.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117