2

I am curious what the current best method is for measuring CPU time in Python3. To be clear, the result I want is the total CPU clock time that the program has been running (i.e. not wall clock time).

I have used the time module for this in the past, but it is unclear to me if this is still the recommended method.

If the time module is the best option, I am wondering if time.process_time() or time.clock() is better.

1 Answers1

2

For cpu time time.process_time() or time.thread_time() is suitable - depending on what you are measuring and whether you are using multi-threading or not.

time.clock() is deprecated

Be mindful of I/O. If you are doing blocking I/O, it will get counted in CPU time. Non blocking I/O (like asyncio) would put the thread to sleep hence not get counted it in CPU time.

Documentation for this is pretty good and i would recommend you go through it in detail https://docs.python.org/3/library/time.html#time.time

famagusta
  • 160
  • 8
  • So `time.process_time()` is suitable for multi-threading measurements, whereas `time.thread_time()` is not suitable for multi-threading? – Elijah Pelofske Dec 11 '20 at 19:04
  • both the functions measure different things. if you want to measure current thread time, thread_time would probably be used. if you want to measure a process's time (which could have spawned multiple threads inside it), you will use process_time. depends on what you are trying to measure. – famagusta Dec 14 '20 at 11:17