Search code examples
python-3.xtimewrapper

Python doesn't calculate time for executing a function


I am learning some Python basics and we had this code about wrapper functions and how they can be used to add functionality to wrapped functions. So we calculate time that was used to compute two different functions:

    import time


def timer(fn):
    def wrapper():
        t0 = time.time()
        result = fn()
        dt = time.time() - t0
        return dt

    return wrapper


def pow_2():
    return 10000000 ** 2


def in_build_pow():
    return pow(10000000, 2)


pow_2 = timer(pow_2)
in_build_pow = timer(in_build_pow)

a, b = 0, 0
N = 100
for i in range(N):
    a += pow_2()
    b += in_build_pow()

print("a = ", a)
print("b = ", b)
print(f"Average time pow_2 = {a / N:.10f}")
print(f"Average time in_build_pow = {b / N:.10f}")

But my result looks like this:

enter image description here

Unless I increase the iteration count N to more than 1000. The higher N, the more often results are not 0.0.

This is N = 1000:

enter image description here

And this is N = 10,000:

enter image description here

Does anyone knows why it is like this? Why I cannot count time for fewer iterations? The code works fine in online compilers, though. But VSCode, VS2022, and PyCharm all have same issues for me.


Solution

  • Some OS has problems calculating very short time intervals with those functions. So its better to use perf_counter_ns() method of time module. Me personally had problems on Win10, while MacOS worked perfectly fine with time() method.