← Back to Blog

Timing Your Code with the time Module

The idea

datetime tells you what time it is. time tells you how long something takes — and lets you control when your program runs.

Two functions. That's most of what you'll use at this level.

time.sleep() — pause execution

import time

print("Starting...")
time.sleep(2)
print("Done.")

The program pauses for 2 seconds between the two prints. The argument is in seconds — decimals work too.

time.sleep(0.5)     # half a second
time.sleep(0.1)     # 100 milliseconds

Useful for: rate limiting, animations, giving users time to read output, simulating delays.

time.time() — measure elapsed time

time.time() returns the current time as a float — seconds since January 1, 1970. The number itself isn't meaningful. The difference between two calls is.

import time

start = time.time()

# code you want to measure
total = 0
for i in range(1_000_000):
    total += i

end = time.time()
print(f"Elapsed: {end - start:.4f} seconds")

Output → Elapsed: 0.0812 seconds

Record the time before. Record it after. Subtract. That's your elapsed time.

A practical example — countdown

import time

for i in range(5, 0, -1):
    print(f"{i}...")
    time.sleep(1)

print("Go.")

Output — one line per second:

5...
4...
3...
2...
1...
Go.

time.perf_counter() — more precise measurement

For more accurate timing — especially for short operations — use perf_counter():

import time

start = time.perf_counter()
total = sum(range(1_000_000))
end   = time.perf_counter()

print(f"Elapsed: {end - start:.6f} seconds")

Same pattern as time.time() — but higher resolution. Use this when precision matters.

Heads up!

  • sleep() blocks the entire program — nothing runs while it's waiting
  • time.time() is fine for general timing — perf_counter() is more precise
  • The argument to sleep() is in seconds — sleep(1000) pauses for 16 minutes
  • time and datetime are separate modules — don't confuse them

What you should understand now

  • time.sleep(n) pauses execution for n seconds
  • time.time() returns current time as a float — subtract two calls for elapsed time
  • time.perf_counter() is more precise for measuring short operations
  • time is about execution — datetime is about calendar dates
[ login to bookmark ] // copied! 18 views · 1 min
// resources
Code Example module_time.py
← prev statistics — What Your Data Is Telling You next → Two Tools That Make Dicts Smarter
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.