How do I get time of a Python program's execution?

后端 未结 30 1636
甜味超标
甜味超标 2020-11-22 02:20

I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.

I\'ve looked at the timeit

30条回答
  •  灰色年华
    2020-11-22 02:49

    I like the output the datetime module provides, where time delta objects show days, hours, minutes, etc. as necessary in a human-readable way.

    For example:

    from datetime import datetime
    start_time = datetime.now()
    # do your work here
    end_time = datetime.now()
    print('Duration: {}'.format(end_time - start_time))
    

    Sample output e.g.

    Duration: 0:00:08.309267
    

    or

    Duration: 1 day, 1:51:24.269711
    

    As J.F. Sebastian mentioned, this approach might encounter some tricky cases with local time, so it's safer to use:

    import time
    from datetime import timedelta
    start_time = time.monotonic()
    end_time = time.monotonic()
    print(timedelta(seconds=end_time - start_time))
    

提交回复
热议问题