文章首发及后续更新:https://mwhls.top/3367.html 新的更新内容请到mwhls.top查看。 无图/无目录/格式错误/更多相关请到上方的文章首发页面查看。

stackoverflow热门问题目录

如有翻译问题欢迎评论指出,谢谢。

如何获取 Python 程序的执行时间?
  • john2x asked:
  • 我有一个命令行形式的 Python 任务需要运行,如何确定它运行完成的具体耗时呢?
  • 我找到了 timeit 模块,但它好像只适合用于短的代码,可我希望能获取整个程序的运行时间。
  • Answers:
  • rogeriopvl - vote: 2444
  • Python 中最简单的方式:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
  • 假定你的程序要花费至少十分一秒来运行。
  • 输出:
--- 0.764891862869 seconds ---
  • PaulMcG - vote: 237
  • 我用的是 timing.py 模块,把它放在 site-packages 包里,然后在自己模块插入 import timing 就能用了:
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")
  • 如果希望获取特定程序的用时的话,可以调用 timing.log 来显示。不过只使用 import timing 只会输出开始与结束时间,以及总用时(请忽略有点乱的 secondsToStr 函数,它只是用来把浮点数转为 hh:mm:ss.sss 的格式)。
  • 注:以上代码的 Python 3 版本见这里以及这里。
  • steveha - vote: 221
  • 在 Linux 或 Unix 中可以这样:
$ time python yourprogram.py
  • 对于 Windows,可见 StackOverflow 问题: How do I measure execution time of a command on the Windows command line?(Windows如何确定命令行执行时间)
  • 译者注:为了写这篇文章,我把上面提到的文章也翻译了:译(三十九)-Windows获取命令行运行时间
  • 获得更臃肿的输出:
$ time -v python yourprogram.py
    Command being timed: "python3 yourprogram.py"
    User time (seconds): 0.08
    System time (seconds): 0.02
    Percent of CPU this job got: 98%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.10
    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): 9480
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 1114
    Voluntary context switches: 0
    Involuntary context switches: 22
    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

How do I get time of a Python program’s execution?
  • john2x asked:
  • 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. 我有一个命令行形式的 Python 任务需要运行,如何确定它运行完成的具体耗时呢?
  • 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. 我找到了 timeit 模块,但它好像只适合用于短的代码,可我希望能获取整个程序的运行时间。
  • Answers:
  • rogeriopvl - vote: 2444
  • The simplest way in Python: Python 中最简单的方式:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
  • This assumes that your program takes at least a tenth of second to run. 假定你的程序要花费至少十分一秒来运行。
  • Prints: 输出:
--- 0.764891862869 seconds ---
  • PaulMcG - vote: 237
  • I put this timing.py module into my own site-packages directory, and just insert import timing at the top of my module: 我用的是 timing.py 模块,把它放在 site-packages 包里,然后在自己模块插入 import timing 就能用了:
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.) 如果希望获取特定程序的用时的话,可以调用 timing.log 来显示。不过只使用 import timing 只会输出开始与结束时间,以及总用时(请忽略有点乱的 secondsToStr 函数,它只是用来把浮点数转为 hh:mm:ss.sss 的格式)。
  • Note: A Python 3 version of the above code can be found here or here. 注:以上代码的 Python 3 版本见这里以及这里。
  • steveha - vote: 221
  • In Linux or Unix: 在 Linux 或 Unix 中可以这样:
$ time python yourprogram.py
  • In Windows, see this StackOverflow question: How do I measure execution time of a command on the Windows command line? 对于 Windows,可见 StackOverflow 问题: How do I measure execution time of a command on the Windows command line?(Windows如何确定命令行执行时间)
  • 译者注:为了写这篇文章,我把上面提到的文章也翻译了:译(三十九)-Windows获取命令行运行时间
  • For more verbose output, 获得更臃肿的输出:
$ time -v python yourprogram.py    Command being timed: "python3 yourprogram.py"    User time (seconds): 0.08    System time (seconds): 0.02    Percent of CPU this job got: 98%    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.10    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): 9480    Average resident set size (kbytes): 0    Major (requiring I/O) page faults: 0    Minor (reclaiming a frame) page faults: 1114    Voluntary context switches: 0    Involuntary context switches: 22    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