[Python time] Tutorial: From Pausing with sleep() to Precise Measurement with perf_counter()
To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you haven’t installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.
Hello! I'm an expert who learned to code with AI and launched two websites in a month and a half. Just a few months ago, I was a complete beginner with zero programming knowledge, just like many of you.
As you learn Python, do you often see `import time` in code generated by AI or in other people's samples? You might be thinking, "There's `time` again, but what does it actually do?" or "Is it just for stopping and measuring time?"
In this article, I'll break down the `time` module in a way that's easy for beginners to understand, sharing my own experiences and stumbling blocks. We'll focus specifically on how to "pause a process (sleep)" and "accurately measure the time a process takes," which are essential skills for practical scenarios like website development and data collection. By the time you finish this article, you'll be able to use the `time` module freely!
1. Why Do We Need to Manipulate Time? - The Importance of Waiting
Do you think that the faster a program runs, the better? In reality, there are times when "intentionally waiting" is extremely important. Let me introduce two specific cases I encountered while developing my websites.
Case 1: Information Gathering from Websites (Scraping)
When you try to automatically collect information from a website, a program accesses pages at a speed unimaginable for a human. This can cause a massive number of requests to hit the server in a short period, creating a heavy load. It's like a huge crowd swarming a shop and disrupting its business. In the worst-case scenario, your access could be blocked.
That's where the technique of "waiting" comes in handy. By adding a process that waits a few seconds after accessing a page, you can significantly reduce the server load and perform information gathering in a well-mannered way.
Case 2: Using APIs
Time management is also essential when using external services (APIs) that provide weather or map information. Many APIs have usage limits, such as "up to 60 times per minute" (rate limits). If you send requests exceeding this limit, the service may become temporarily unavailable, or you might receive errors.
Here too, by "waiting" for a certain period after each request, you can stay within the usage limits.
This process of creating an intentional "wait time" in a program is called a sleep process. And the easiest way to achieve this in Python is with the `time.sleep()` function.
2. Pausing Perfectly! Halting Execution with `time.sleep()`
`time.sleep()` is a very simple function that temporarily stops the program's execution for a specified number of seconds. Let's start with its basic usage.
The following code is a simple example that displays "Starting the process." and then, after 3 seconds, displays "3 seconds have passed. Finishing the process." Copy and paste it into your environment to get a feel for "waiting."
# Import the time module
import time
print("Starting the process.")
# Pause the process for 3 seconds
time.sleep(3)
print("3 seconds have passed. Finishing the process.")
You can also specify decimals for the argument, like 0.5 (0.5 seconds) or 0.1 (100 milliseconds). This allows for more precise time control.
import time
print("Waiting for just 0.5 seconds.")
# Pause the process for 0.5 seconds
time.sleep(0.5)
print("Done!")
By combining it with a loop, you can easily create a program that executes something periodically. For example, here's a program that counts down every second.
import time
print("Countdown start!")
for i in range(5, 0, -1):
print(i)
# Wait for 1 second
time.sleep(1)
print("Liftoff!")
3. Stopwatch Function! How to Measure Processing Time Accurately
Another important role of the `time` module is measuring processing time. Understanding which parts of your code are taking the most time is the first step toward performance improvement.
When you feel "this process seems slow..." it's important to actually measure the time and identify the bottleneck, rather than relying on intuition.
The Beginner's Approach: `time.time()`
The most basic way to measure time is to call `time.time()` before and after a process and calculate the difference. `time.time()` returns the number of seconds that have passed since a reference time called the "UNIX epoch" (January 1, 1970, 00:00:00).
import time
# Record the time before the process starts
start_time = time.time()
# Write the code you want to measure here
# As an example, let's put in a 1-second pause
print("Running the process to be measured...")
time.sleep(1)
print("Process completed.")
# Record the time after the process finishes
end_time = time.time()
# Calculate and display the elapsed time
elapsed_time = end_time - start_time
print(f"Time taken for the process: {elapsed_time} seconds")
[My Failure Story] The Pitfall of `time.time()`
Actually, while `time.time()` is convenient, it has one major pitfall. That is, it is affected by changes to the PC's system clock.
When I was starting out, I used `time.time()` to measure a long-running process. However, in the middle of the process, my PC automatically synchronized its clock (NTP sync), which resulted in a completely wrong measurement, different from the actual processing time. For example, if the system clock is set back by 1 second during the process, the calculated elapsed time will be 1 second shorter. You can't get an accurate measurement that way, right?
That's where a more reliable time measurement method comes in.
The Professional's Choice: `time.perf_counter()`
`time.perf_counter()` (short for performance counter) is a function specialized for measuring short durations, just like measuring processing time. The value it returns is not a specific "time of day" but rather a monotonically increasing time with the highest available resolution provided by the OS.
"Monotonically increasing" is the key point here. It means that even if the system clock is changed, the counter's value will never go backward. Therefore, even if a clock synchronization occurs during your process, it won't affect the measurement result.
Even in Python's official documentation, using `perf_counter()` is recommended for measuring processing time.
The usage is exactly the same as `time.time()`.
import time
# Record the counter value before the process starts
start_counter = time.perf_counter()
# Write the code you want to measure here
print("Running the process to be measured...")
total = 0
for i in range(10000000): # Example of a time-consuming process
total += i
print("Process completed.")
# Record the counter value after the process finishes
end_counter = time.perf_counter()
# Calculate and display the elapsed time
elapsed_time = end_counter - start_counter
print(f"Time taken for the process: {elapsed_time} seconds")
Unless you have a specific reason not to, you can't go wrong by remembering to use `time.perf_counter()` for measuring processing time!
4. [Advanced] For Web Creators! A Fully Functional HTML Timer
So far, we've learned about Python's `time` module. These are very useful for programs that run on the server-side (the backend). However, as a web creator, you want to present the results in a form that users can see, i.e., on a web page, right?
So, let's apply the concepts of Python's `time` module to create a simple countdown timer that runs in the browser using HTML and JavaScript. Just as Python's `time.sleep(1)` was a command to "wait for 1 second," in JavaScript, you can use the `setInterval()` command to "do something every second."
The following code is a complete HTML file. Copy this code, save it with a name like `timer.html`, and open it in your browser. When you press the button, you should see the number on the screen decrease every second. This is the first step in letting users experience something "that works"!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Countdown Timer</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #121212;
color: #e0e0e0;
font-family: sans-serif;
text-align: center;
}
#timer-display {
font-size: 8rem;
font-weight: bold;
color: #669df6;
}
button {
margin-top: 2rem;
padding: 1rem 2rem;
font-size: 1.5rem;
cursor: pointer;
border: 1px solid #5f6368;
background-color: transparent;
color: #8ab4f8;
border-radius: 5px;
}
button:disabled {
cursor: not-allowed;
opacity: 0.5;
}
</style>
</head>
<body>
<div>
<h1>Countdown with JavaScript</h1>
<div id="timer-display">10</div>
<button id="start-btn">Start</button>
<p>Applying the concept of Python's time.sleep()!</p>
</div>
<script>
// The script tag is written here
const timerDisplay = document.getElementById('timer-display');
const startButton = document.getElementById('start-btn');
let timeLeft = 10;
let timerId = null;
function startTimer() {
// Disable the button to prevent double-clicking
startButton.disabled = true;
// Execute the process every 1 second (1000 milliseconds)
timerId = setInterval(() => {
timeLeft--;
timerDisplay.textContent = timeLeft;
if (timeLeft <= 0) {
clearInterval(timerId); // Stop the timer
timerDisplay.textContent = "Go!";
}
}, 1000);
}
// Start the timer when the start button is clicked
startButton.addEventListener('click', startTimer);
</script>
</body>
</html>
5. Summary of Points to Note When Using the `time` Module
Finally, let's review the important points to remember when working with the `time` module.
- Use `time.sleep()` for sleeping: Use it when you want to intentionally pause a process, as a courtesy in web scraping or when using APIs.
- Use `time.perf_counter()` for time measurement: Use it when you want to accurately measure the performance of a process. It's more reliable than `time.time()` because it's not affected by system clock changes.
- The precision of `sleep()` is not perfect: Even with `time.sleep(1)`, depending on the status of other OS processes, the actual wait time might be 1.002 seconds or 1.01 seconds instead of exactly 1.000 seconds. Remember that it's not suitable for ultra-high-precision control.
Conclusion
In this article, we learned how to "pause" and "measure" processes using Python's `time` module. It may seem like a modest module at first glance, but it's an indispensable and very powerful tool for creating practical programs.
Specifically, `time.sleep()` is an important function for showing consideration to others (servers), while `time.perf_counter()` is for showing consideration to yourself (improving code performance).
Try to incorporate the concept of "time" into your programs using what you've learned today. I'm sure it will greatly expand the range of things you can create.
To the Next Step
Now that you've mastered handling time with the `time` module, why not learn about useful tools for handling data efficiently? Python has many more powerful data structures available by default.
In the next article, we'll focus on the `collections` module and introduce features like `defaultdict` and `deque` that make dictionaries and lists even more convenient. Mastering these will enable you to write more sophisticated code!
» A Summary of Useful Data Structures in the collections Module