Python speed testing - Time Difference - milliseconds

后端 未结 13 1295
小蘑菇
小蘑菇 2020-11-27 10:41

What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I\'m not sure I understand the timedelta thing.

13条回答
  •  -上瘾入骨i
    2020-11-27 10:44

    datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds

    >>> import datetime
    >>> a = datetime.datetime.now()
    >>> b = datetime.datetime.now()
    >>> c = b - a
    
    >>> c
    datetime.timedelta(0, 4, 316543)
    >>> c.days
    0
    >>> c.seconds
    4
    >>> c.microseconds
    316543
    

    Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

    You can do all sorts of maths with datetime.timedelta, eg:

    >>> c / 10
    datetime.timedelta(0, 0, 431654)
    

    It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.

提交回复
热议问题