pythonfunctiontimetimeit

perf_counter()-start giving weird result


I was building my own version of the timeit function, which returns the amount of time it takes to run a function n times. However, when I ran it with a sample input, I received the following output, which doesn't seem right, as it ran very quickly.

9.400071576237679e-06

My code:

from time import perf_counter
from typing import Callable

class MyTimeit:
    def __init__(self):
        pass 
    def timeit(self, function: Callable, *parameters, num: int=10000):
        if not parameters:
            start = perf_counter()
            for _ in range(num):
                function()
            return perf_counter()-start
        else:
            start = perf_counter()
            for _ in range(num):
                function(*parameters)
            return perf_counter()-start

print(MyTimeit().timeit(lambda x: x<12, 10, n=100))

Why is it giving me this result? Is it a flaw in my programming logic, or am I missing something else?


Solution

  • It works fine, your function is just very fast, so it's executing in microseconds. You can test this using something that takes seconds to run, like sleep. Note that for very fast functions, the initial overhead is large compared to each run of the for loop. You can measure the overhead with n = 0.

    from time import perf_counter, sleep
    from typing import Callable
    
    class MyTimeit:
        def __init__(self):
            pass 
        def timeit(self, f: Callable, *args, n: int=10000):
            if not args:
                s = perf_counter()
                for _ in range(n):
                    f()
                return perf_counter()-s
            else:
                s = perf_counter()
                for _ in range(n):
                    f(*args)
                return perf_counter()-s
    
    print(MyTimeit().timeit(sleep, 1, n=5))