Python perf_counter Timing — ELI5

Remember using a stopwatch in gym class? The teacher clicks start when you begin running, clicks stop when you finish, and reads the time. Simple.

perf_counter is Python’s stopwatch for code. You record the time before something runs, record the time after, and subtract. The difference tells you exactly how many seconds (or fractions of a second) that chunk of code took.

Why not just look at a clock? Because regular clocks aren’t precise enough. Imagine timing a sprint that takes 0.003 seconds — a wall clock that only shows hours and minutes is useless. perf_counter measures down to tiny fractions of a second, using the most accurate timer your computer has.

Python actually has several timing functions, but perf_counter is the one you want for measuring how fast code runs. It counts real elapsed time — the actual seconds that ticked by — including any time your program spent waiting.

Here’s the pattern in plain English:

  1. Note the time (start)
  2. Run the code you want to measure
  3. Note the time again (end)
  4. Subtract: end - start = how long it took

Developers use this to find slow spots in their programs. Maybe loading data takes 2 seconds but processing it takes 0.01 seconds — now you know where to focus your effort.

It’s the simplest, most reliable way to answer the question: “How long does this take?”

The one thing to remember: perf_counter is Python’s precision stopwatch — note the time before and after your code runs, subtract, and you know exactly how long it took.

pythonperformancestdlib

See Also