2

Recently I have found this question:

Find out time it took for a python script to complete execution

The highest voted answer suggests that for timing an execution, I should use difference in datetime.now() calls. I have seen people using time.time(), but never datetime.now() for this purpose. This video at 5:30 suggests to use time.perf_counter() (which was not mentioned in any of the answers so I added it).

Is using datetime.now() equivalent to using time.perf_counter(), with the output having better human readability, or there are caveats?

zabop
  • 6,750
  • 3
  • 39
  • 84

2 Answers2

0

I belive that the following methods will give you very similar results:

from datetime import datetime
datetime_start = datetime.now()
# whatever process
datetime_end = datetime.now()
total_time_datetime = datetime_end - datetime_start
import time
time_start = datetime.perf_counter()
# whatever process
time_end = datetime.perf_counter()
total_time_time = time_end - time_start

total_time_datetime outputed a datetime object with 6 decimal points, while the total_time_time outputed a float with 14 decimal points. Then, I bet that time method is a little more accurate, although it may be not noticiable for most measures.

Also time method is protected against manual time modification of the server, or the daylight saving time change (the latter probably could be avoided using datetime.utcnow()).

On the other hand, datetime object unlike the float object of time, allows you to apply multiple methods to get/extract different times (microseconds, seconds, minutes...). For example datetime object has the method total_seconds() which will give a float (as time):

(datetime_end - datetime_start).total_seconds()
drasc
  • 517
  • 4
  • 7
0

I think you should use time.perf_counter() for execution times.

Under the hood datetime.datetime.now() uses time.time(). With this knowledge this question boils down to the question of should we use time.time() or time.perf_counter() for measuring execution time. As explained in this answer, it is better to use time.perf_counter() for program execution time because time.perf_counter() returns the time from a continuous running ticker with constant intervals whereas time.time() is recording something like "what time the computer thinks it is in UTC" which, I think, in certain edge cases, may not result in a constant interval between ticks. These edge cases might be something like users adjusting the system time or possibly something related to leap time or daylight savings time.

Jagerber48
  • 488
  • 4
  • 13