I’m working on a Python application that includes a timer or stopwatch feature. The application is intended to run entirely offline, and the timer should be immune to changes in the system clock (e.g., user modifying the system time). I’ve written some code using time.perf_counter(), but I’m encountering an issue when re-running the script.
**Problem:
**The code runs correctly and the elapsed time is unaffected when I decrease the system time. However, when I re-run the script, the timer should start from zero, but it seems to be delayed by the amount of time the system clock was altered.
For example, if I decrease the system time by 3 minutes and then re-run the script, the timer does not start counting immediately but after 3 minutes (equal to the time change).
import time
import threading
class Timer:
def __init__(self):
self.start_time = None
self.elapsed_time = 0.0
self.running = False
self.lock = threading.Lock()
def start(self):
if not self.running:
self.start_time = time.perf_counter()
self.elapsed_time = 0.0
self.running = True
threading.Thread(target=self._run, daemon=True).start()
def _run(self):
last_time = time.perf_counter()
while self.running:
current_time = time.perf_counter()
with self.lock:
self.elapsed_time += current_time - last_time
last_time = current_time
time.sleep(0.1)
def get_elapsed_time(self):
with self.lock:
return self.elapsed_time
def stop(self):
self.running = False
if __name__ == '__main__':
timer = Timer()
timer.start()
try:
while True:
elapsed = timer.get_elapsed_time()
print(f"rElapsed time: {elapsed:.2f} seconds", end='')
time.sleep(0.1)
except KeyboardInterrupt:
timer.stop()
**Issue:
**The elapsed time calculation works correctly when the script is running.
Upon re-running the script after changing the system time (e.g., decreasing by 3 minutes), the timer should start from zero but instead waits for the decreased time before starting.
**Question:
**How can I modify the script to ensure that the timer always starts from zero and runs accurately regardless of any changes to the system clock, even across multiple script executions?
Is there a better approach than using time.perf_counter() to achieve this?
Abdulrehman Qureshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.