Python Glossary Русский

Python 3.7+timefunction

time.perf_counter_ns()

clocks and timing

The perf_counter() counter as an integer number of nanoseconds — for measurements where every nanosecond counts and float rounding is unwanted.

Syntax

time.perf_counter_ns() -> int

To get milliseconds divide by 1_000_000, not by 1000: that common slip makes the result a thousand times too large. Integer differences accumulate cleanly over many runs, while a float sum would lose low digits. Never mix it with perf_counter() in one difference — the units differ.

Examples

import time
t0 = time.perf_counter_ns()
sorted(range(10_000, 0, -1))
ns = time.perf_counter_ns() - t0
print(ns >= 0, type(ns).__name__)  # → True int
print(ns / 1_000_000, 'мс')  # → ? 0.21 мс

See also

Open in the full glossarydocs.python.orgReport an inaccuracy