r/learnpython • • Oct 19 '26

timing a process

I have a program (Python 2) that writes a status message whenever an hour (realtime) has gone by with nothing happening (eta: more precisely, with no new solution found). Now I find that time.clock() no longer exists in Python 3. Since I have to change it anyway, what's best practice?

In other words, what is the customary way to measure how long a program has been running?

2 Upvotes

12 comments sorted by

5

u/bytheninedivines Oct 19 '26

time.perf_counter is the highest precision way to measure time.

-1

u/lazydog60 Oct 20 '26 edited Oct 20 '26

For this purpose I prefer simplicity to precision, thanks

9

u/lekkerste_wiener Oct 19 '26

Look into the datetime package. There you'll find 2 classes that will help you out, datetime and timedelta.

1

u/Boybay_Garid Oct 20 '26

yeah timedelta is super clean for this kind of thing

1

u/baubleglue Oct 19 '26

replace with time.ctime()

0

u/lazydog60 Oct 19 '26

That looks like almost the opposite of what I want.

2

u/KiwiDomino Oct 19 '26

If I was writing in C under UNIX or related, I’d ask the OS to send me an alarm and then just sleep and wait for the signal.

Python supports this sort of thing with the signal module.
Apparently Windows doesn’t have that facility, though

1

u/RyanDubois43 Oct 20 '26

time.perf_counter() is more precise than time.time() for timing a process, especially on Python 3.3+.

1

u/Educational_Virus672 Oct 20 '26

you should use time.perf_counter* it tells how long programmer has ran for so

a = time.perf_counter()
time.sleep(60)
b = time.perf_counter()
print(b-a) # it prints ~60 

1

u/DimensionMost8342 Oct 20 '26

time.clock() was removed in Python 3.8, and time.perf_counter() is the standard replacement for measuring elapsed time. ``python

start = time.perf_counter() do_the_thing() elapsed = time.perf_counter() - start

It is monotonic and has the highest resolution, so it is the right tool for this. time.monotonic() also works. Avoid time.time() here, because the system clock can jump when it syncs with NTP.

0

u/danielroseman Oct 19 '26

The way to measure absolute elapsed time is time.monotonic: https://docs.python.org/3/library/time.html#time.monotonic

1

u/lazydog60 Oct 19 '26

This looks like what I want. Thanks.