Thursday 6 May 2021

Python CPU Clock. time.clock() vs time.perf_counter() vs time.process_time()

 Both perf_counter and timeit will give you the time that your block of code tested had taken to perform.

time.process_time() it does not and it calculates what the CPU have taken, which is not necessarily the same as the function or block of code.

I found this thread on Github, seems that the question is quite advanced and may be completely different depending on the OS or program to be benchmark-ed.

Something that time.process_time() is not counting is the Parent Multi-thread:

"One consequence of using time.process_time is that the time spent in child processes of the benchmark is not included. Multithreaded benchmarks also return the total CPU time counting all CPUs."

perf_counter

from time import perf_counter


start = perf_counter()

for _ in range(10000):
    x = "-".join(str(n) for n in range(100))
end = perf_counter()
print('Perf Counter= ', end-start)
# Perf Counter=  0.23170840000000004

timeit

import timeit

print(timeit.timeit('"-".join(str(n) for n in range(100))', number=10000))
# 0.20687929999999993


from : 

No comments:

Post a Comment