Python Time Module - Perf Counter

It is important to have a high-resolution monotonic clock for measuring performance.

Determining the best clock data source requires platform-specific knowledge, which Python provides in perf_counter().

import hashlib
import time

# perf_counter determines the best source of clock 
# to measure performance

data = open(__file__, 'rb').read()

loop_start = time.perf_counter()

for i in range(5):
    iter_start = time.perf_counter()
    h = hashlib.sha1()
    for i in range(300000):
    chsum = h.digest()
    now = time.perf_counter()
    loop_elapsed = now - loop_start
    iter_elapsed = now - iter_start
    print(time.ctime(),':{:0.3f} {:0.3f}'.format(iter_elapsed,loop_elapsed))

# epoch for perf_counter() is undefined as it is 
# meant to be used for comparing and computing values

This is part of series of articles from Python Module of the Week


- 1 toast