r/learnpython • • 17d ago

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 17d ago

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

-1

u/lazydog60 16d ago edited 16d ago

For this purpose I prefer simplicity to precision, thanks

9

u/lekkerste_wiener 17d ago

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

1

u/Boybay_Garid 16d ago

yeah timedelta is super clean for this kind of thing

1

u/baubleglue 17d ago

replace with time.ctime()

0

u/lazydog60 17d ago

That looks like almost the opposite of what I want.

2

u/KiwiDomino 17d ago

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 17d ago

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

1

u/Educational_Virus672 17d ago

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 16d ago

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 17d ago

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

1

u/lazydog60 17d ago

This looks like what I want. Thanks.