How do I get time of a Python program's execut

2018-12-31 19:31发布

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 module, but it seems it's only for small snippets of code. I want to time the whole program.

标签: python time
25条回答
柔情千种
2楼-- · 2018-12-31 20:02

Ipython "timeit" any script:

def foo():
    %run bar.py
timeit foo()
查看更多
闭嘴吧你
3楼-- · 2018-12-31 20:02

If you want to measure time in microseconds, then you can use the following version, based completely on the answers of Paul McGuire and Nicojo - it's a Python3 code. I've also added some colour to it:

import atexit
from time import time
from datetime import timedelta, datetime


def seconds_to_str(elapsed=None):
    if elapsed is None:
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    else:
        return str(timedelta(seconds=elapsed))


def log(txt, elapsed=None):
    colour_cyan = '\033[36m'
    colour_reset = '\033[0;0;39m'
    colour_red = '\033[31m'
    print('\n ' + colour_cyan + '  [TIMING]> [' + seconds_to_str() + '] ----> ' + txt + '\n' + colour_reset)
    if elapsed:
        print("\n " + colour_red + " [TIMING]> Elapsed time ==> " + elapsed + "\n" + colour_reset)


def end_log():
    end = time()
    elapsed = end-start
    log("End Program", seconds_to_str(elapsed))


start = time()
atexit.register(end_log)
log("Start Program")

log() => function that prints out the timing info.

txt ==> first argument to log, and it's string to mark timing.

atexit ==> python module to register functions that you can call when program exits.

查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 20:03

To use metakermit's updated answer for python 2.7 you will require the monotonic package.

The code would then be as follows:

from datetime import timedelta
from monotonic import monotonic

start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))
查看更多
闭嘴吧你
5楼-- · 2018-12-31 20:04

The following snippet prints elapsed time in a nice human readable <HH:MM:SS> format.

import time
from datetime import timedelta

start_time = time.time()

#
# Perform lots of computations.
#

elapsed_time_secs = time.time() - start_time

msg = "Execution took: %s secs (Wall clock time)" % timedelta(seconds=round(elapsed_time_secs))

print(msg)    
查看更多
旧时光的记忆
6楼-- · 2018-12-31 20:06

Even better for Linux: /usr/bin/time

$ /usr/bin/time -v python rhtest2.py

    Command being timed: "python rhtest2.py"
    User time (seconds): 4.13
    System time (seconds): 0.07
    Percent of CPU this job got: 91%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.58
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 0
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 15
    Minor (reclaiming a frame) page faults: 5095
    Voluntary context switches: 27
    Involuntary context switches: 279
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0

Normally, just time is a simpler shell builtin that shadows the more capable /usr/bin/time.

查看更多
其实,你不懂
7楼-- · 2018-12-31 20:09

I put this timing.py module into my own site-packages directory, and just insert import timing at the top of my module:

import atexit
from time import clock

def secondsToStr(t):
    return "%d:%02d:%02d.%03d" % \
        reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
            [(t*1000,),1000,60,60])

line = "="*40
def log(s, elapsed=None):
    print line
    print secondsToStr(clock()), '-', s
    if elapsed:
        print "Elapsed time:", elapsed
    print line
    print

def endlog():
    end = clock()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

def now():
    return secondsToStr(clock())

start = clock()
atexit.register(endlog)
log("Start Program")

I can also call timing.log from within my program if there are significant stages within the program I want to show. But just including import timing will print the start and end times, and overall elapsed time. (Forgive my obscure secondsToStr function, it just formats a floating point number of seconds to hh:mm:ss.sss form.)

Note: A Python 3 version of the above code can be found here or here.

查看更多
登录 后发表回答