Module 15 · Python Standard Libraries — topic 4 of 13
time
The time module: timestamps with time.time, measuring durations with perf_counter and monotonic, pausing with sleep, struct_time and formatting, and building a simple timing decorator.
Learning objectives
- Measure how long code takes
- Pause execution with sleep
- Convert timestamps to readable form
Definition
The time module provides low-level time functions: the current time as seconds since the epoch, high-resolution counters for measuring durations, sleeping, and conversions between timestamps and calendar fields.
Introduction
How long did that function take? Wait two seconds before retrying. What date was timestamp 1,700,000,000? The time module answers these questions.
Why it matters
Timing code is the first step in making it faster, and sleeping is essential for polling, retries and simple animations.
Detailed explanation
The epoch is 1 January 1970 UTC. time.time() returns seconds since then as a float — useful for timestamps.
time.perf_counter() is the best clock for measuring short durations: take a reading before and after and subtract.
time.monotonic() never goes backwards, even if the system clock is changed, which makes it right for timeouts.
time.sleep(seconds) pauses the current thread; fractions such as 0.5 are allowed.
time.gmtime(ts) and time.localtime(ts) convert a timestamp to a struct_time with fields like tm_year and tm_hour; time.strftime formats one.
For calendar arithmetic and formatting, datetime is usually more convenient; time is for measurement and pauses.
timeit (another standard module) runs a statement many times to measure small pieces of code accurately.
A single measurement can be distorted by other programs running at the same time, so when comparing two approaches, repeat each measurement several times and compare the best or median results.
Syntax
- perf_counter for durations.
- sleep pauses.
- time() for timestamps.
Code examples
Measuring a duration
499999500000 True
Timestamps and struct_time
1970 1 1 1971-01-01 00:00:00
More examples
A timing decorator
done True True True
Step-by-step explanation
- The decorator records the elapsed time in an attribute of the wrapper, even if the function raises.
- sleep(0.05) pauses for about 50 milliseconds, so the measured time is at least that long.
- The checks avoid printing exact times, which differ on every run.
Expected output
Running “A timing decorator” prints exactly:
Practical applications
- Profiling slow functions.
- Retry loops that wait between attempts.
Best practices
- Use perf_counter for benchmarks.
- Use monotonic for timeouts.
- Use datetime for calendar work.
Common mistakes
Timing with time.time()
Avoid
Prefer
time.time can jump when the clock is adjusted and has lower resolution.
Sleeping in milliseconds
Avoid
Prefer
sleep takes seconds, not milliseconds.
Important notes
- python -m timeit "sum(range(1000))" benchmarks a snippet from the command line.
Key takeaways
- time.time gives timestamps.
- perf_counter measures durations.
- sleep pauses in seconds.
Try it yourself
- 1Compare the speed of a list comprehension and a for loop that build the same list.
- 2Write a countdown that prints 3, 2, 1 with one-second pauses.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
14 questions cover the “Python Standard Libraries” module. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhy call random.seed(42) before generating numbers in a test?
- ModerateWhat is printed?