我如何获得Python程序的执行时间?

时间:2009-10-12 23:56:48

标签: python time

我在Python中有一个命令行程序需要一段时间才能完成。我想知道完成跑步的确切时间。

我查看了timeit模块,但它似乎只适用于小代码片段。我想为整个计划计时。

35 个答案:

答案 0 :(得分:1275)

Python中最简单的方法:

import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))

这假设您的程序至少需要十分之一秒才能运行。

打印:

--- 0.764891862869 seconds ---

答案 1 :(得分:185)

我将此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版本herehere

答案 2 :(得分:141)

在Linux或UNIX中:

time python yourprogram.py

在Windows中,请参阅此Stackoverflow讨论: How to measure execution time of command in windows command line?

答案 3 :(得分:57)

import time

start_time = time.clock()
main()
print time.clock() - start_time, "seconds"

time.clock()返回处理器时间,这使我们只能计算此过程使用的时间(无论如何在Unix上)。文档说“无论如何,这是用于基准测试Python或计时算法的函数”

答案 4 :(得分:54)

我非常喜欢Paul McGuire的回答,但我使用的是Python3。所以对于那些感兴趣的人:这里是他的答案的修改,适用于* nix上的Python 3(我想,在Windows下,应该使用clock()而不是time()):

#python3
import atexit
from time import time, strftime, localtime
from datetime import timedelta

def secondsToStr(elapsed=None):
    if elapsed is None:
        return strftime("%Y-%m-%d %H:%M:%S", localtime())
    else:
        return str(timedelta(seconds=elapsed))

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

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

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

如果你觉得这很有用,你应该继续投票给他的答案而不是这个,因为他完成了大部分的工作;)。

答案 5 :(得分:44)

您可以使用python profiler cProfile来测量CPU time以及每个函数内部花费的时间以及每个函数调用的次数。如果您想在不知道从哪里开始的情况下提高脚本的性能,这非常有用。 This answer对另一个问题非常好。看看the docs也很好。

以下是如何使用命令行中的cProfile配置脚本的示例:

$ python -m cProfile euler048.py

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}

答案 6 :(得分:35)

我喜欢datetime模块提供的输出,其中时间delta对象以人类可读的方式显示天,小时,分钟等。

例如:

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

样本输出,例如

Duration: 0:00:08.309267

Duration: 1 day, 1:51:24.269711

更新:正如J.F.Sebastian所说,这种方法可能会遇到一些当地时间的棘手案例,因此使用起来更安全:

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

答案 7 :(得分:24)

对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

通常情况下,只有time是一个更简单的内置内容,可以隐藏更强大的/usr/bin/time

答案 8 :(得分:12)

rogeriopvl的解决方案工作正常,但如果您想要更具体的信息,可以使用python内置的分析器。查看此页面:

http://docs.python.org/library/profile.html

剖析器会告诉您许多有用的信息,例如每个函数花费的时间

答案 9 :(得分:11)

以下代码段以良好的人类可读<HH:MM:SS>格式打印已用时间。

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)    

答案 10 :(得分:10)

<强> time.clock()

  

从版本3.3开始不推荐使用:此功能的行为取决于   在平台上:使用 perf_counter() process_time() 代替,   根据您的要求,要有明确的行为。

<强> time.perf_counter()

  

返回性能计数器的值(以小数秒为单位),   即具有最高可用分辨率的时钟来测量短路   持续时间。它 包括睡眠期间经过的时间   全系统。

<强> time.process_time()

  

返回系统和的总和值(以小数秒为单位)   用户当前进程的CPU时间。 包含已过去的时间   在睡觉期间。

start = time.process_time()
... do something
elapsed = (time.process_time() - start)

答案 11 :(得分:8)

from time import time
start_time = time()
...
end_time = time()
time_taken = end_time - start_time # time_taken is in seconds
hours, rest = divmod(time_taken,3600)
minutes, seconds = divmod(rest, 60)

答案 12 :(得分:8)

只需使用timeit模块。它适用于Python 2和Python 3

import timeit

start = timeit.default_timer()
#ALL THE PROGRAM STATEMETNS
stop = timeit.default_timer()
execution_time = stop - start

print("Program Executed in "+execution_time) #It returns time in sec

以秒为单位返回,您可以拥有执行时间。很简单但你应该在Main Function中编写这些函数来启动程序执行。如果你想获得执行时间,即使你得到错误,然后采取参数&#34;开始&#34;它,并在那里计算

def sample_function(start,**kwargs):
     try:
         #your statements
     Except:
         #Except Statements
         stop = timeit.default_timer()
         execution_time = stop - start
         print("Program Executed in "+execution_time)

答案 13 :(得分:7)

Ipython“timeit”任何脚本:

def foo():
    %run bar.py
timeit foo()

答案 14 :(得分:7)

  

我已经查看了timeit模块,但它似乎只适用于小段代码。我想为整个计划计时。

$ python -mtimeit -n1 -r1 -t -s "from your_module import main" "main()"

它运行一次your_module.main()函数并使用time.time()函数作为计时器打印已用时间。

要在Python中模拟/usr/bin/time,请参阅Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?

要测量每个函数的CPU时间(例如,不包括time.sleep()期间的时间),您可以在Python 2上使用profile模块(cProfile):

$ python3 -mprofile your_module.py

如果您想使用与-p模块使用的计时器相同的计时器,您可以将timeit传递给profile命令。

请参阅How can you profile a Python script?

答案 15 :(得分:5)

我也喜欢Paul McGuire的回答,并提出了一个更符合我需求的上下文管理器表格。

import datetime as dt
import timeit

class TimingManager(object):
    """Context Manager used with the statement 'with' to time some execution.

    Example:

    with TimingManager() as t:
       # Code to time
    """

    clock = timeit.default_timer

    def __enter__(self):
        """
        """
        self.start = self.clock()
        self.log('\n=> Start Timing: {}')

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        """
        self.endlog()

        return False

    def log(self, s, elapsed=None):
        """Log current time and elapsed time if present.
        :param s: Text to display, use '{}' to format the text with
            the current time.
        :param elapsed: Elapsed time to display. Dafault: None, no display.
        """
        print s.format(self._secondsToStr(self.clock()))

        if(elapsed is not None):
            print 'Elapsed time: {}\n'.format(elapsed)

    def endlog(self):
        """Log time for the end of execution with elapsed time.
        """
        self.log('=> End Timing: {}', self.now())

    def now(self):
        """Return current elapsed time as hh:mm:ss string.
        :return: String.
        """
        return str(dt.timedelta(seconds = self.clock() - self.start))

    def _secondsToStr(self, sec):
        """Convert timestamp to h:mm:ss string.
        :param sec: Timestamp.
        """
        return str(dt.datetime.fromtimestamp(sec))

答案 16 :(得分:5)

有一个timeit模块可用于计算python代码的执行时间。 它在python docs(https://docs.python.org/2/library/timeit.html

中有详细的文档和示例

答案 17 :(得分:5)

稍后的答案,但我使用timeit

import timeit
code_to_test = """
a = range(100000)
b = []
for i in a:
    b.append(i*2)
"""
elapsed_time = timeit.timeit(code_to_test, number=500)
print(elapsed_time)
# 10.159821493085474

  • code_to_test内包装所有代码,包括您可能拥有的所有导入内容。
  • number参数指定代码应重复的次数。
  • Demo

答案 18 :(得分:4)

使用line_profiler

line_profiler将分析各行代码执行的时间。分析器通过Cython在C中实现,以减少分析的开销。

from line_profiler import LineProfiler
import random

def do_stuff(numbers):
    s = sum(numbers)
    l = [numbers[i]/43 for i in range(len(numbers))]
    m = ['hello'+str(numbers[i]) for i in range(len(numbers))]

numbers = [random.randint(1,100) for i in range(1000)]
lp = LineProfiler()
lp_wrapper = lp(do_stuff)
lp_wrapper(numbers)
lp.print_stats()

结果将是:

Timer unit: 1e-06 s

Total time: 0.000649 s
File: <ipython-input-2-2e060b054fea>
Function: do_stuff at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     4                                           def do_stuff(numbers):
     5         1           10     10.0      1.5      s = sum(numbers)
     6         1          186    186.0     28.7      l = [numbers[i]/43 for i in range(len(numbers))]
     7         1          453    453.0     69.8      m = ['hello'+str(numbers[i]) for i in range(len(numbers))]

答案 19 :(得分:4)

首先,以管理员身份打开命令提示符(CMD),安装humanfriendly软件包,然后在其中键入- pip install humanfriendly

代码:

from humanfriendly import format_timespan
import time
begin_time = time.time()
# Put your code here
end_time = time.time() - begin_time
print("Total execution time: ", format_timespan(end_time))

输出:

enter image description here

答案 20 :(得分:4)

与@rogeriopvl的响应类似,我使用了相同的库来对长时间运行的作业进行了稍微的修改,以将其转换为小时分钟秒。

import time
start_time = time.time()
main()
seconds = time.time() - start_time
print('Time Taken:', time.strftime("%H:%M:%S",time.gmtime(seconds)))

样本输出

Time Taken: 00:00:08

答案 21 :(得分:3)

对于使用Jupyter Notebook的数据人员

在一个单元格中,您可以使用Jupyter的%%time魔术命令来测量执行时间:

%%time 
[ x**2 for x in range(10000)] 

输出
CPU时间:用户4.54 ms,sys:0 ns,总计:4.54 ms
挂墙时间:4.12毫秒

这只会捕获特定单元的执行时间。如果您想捕获整个笔记本(即程序)的执行时间,则可以在同一目录中创建一个新笔记本,然后在新笔记本中执行所有单元格:

假设上面的笔记本名为example_notebook.ipynb。在同一目录中的新笔记本中:

# Convert your notebook to a .py script:
!jupyter nbconvert --to script example_notebook.ipynb

# Run the example_notebook with -t flag for time
%run -t example_notebook

输出
IPython CPU时间(估计):   用户:0.00秒。
  系统:0.00 s。
墙壁时间:0.00秒。

答案 22 :(得分:2)

这是Paul McGuire的回答,对我有用。以防有人在运行那个时遇到问题。

import atexit
from time import clock

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

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)

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

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

def main():
    start = clock()
    atexit.register(endlog)
    log("Start Program")
导入文件后,

从您的程序中调用timing.main()

答案 23 :(得分:2)

我尝试使用以下脚本找到时差。

import time

start_time = time.perf_counter()
[main code here]
print (time.perf_counter() - start_time, "seconds")

答案 24 :(得分:2)

Timeit是python中用于计算小块代码执行时间的类。

Default_timer是此类中的一种方法,用于测量挂钟时间而非CPU执行时间。因此,其他流程执行可能会干扰这一点。因此,它对于小块代码很有用。

代码示例如下:

from timeit import default_timer as timer

start= timer()

#some logic 

end = timer() 

print("Time taken:", end-start) 

答案 25 :(得分:2)

我使用了一个非常简单的函数来定时执行部分代码:

import time
def timing():
    start_time = time.time()
    return lambda x: print("[{:.2f}s] {}".format(time.time() - start_time, x))

要使用它,只需在代码前调用它以测量计时功能,然后在代码后调用带有注释的函数,时间将出现在注释的前面,例如:

t = timing()
train = pd.read_csv('train.csv',
                        dtype={
                            'id': str,
                            'vendor_id': str,
                            'pickup_datetime': str,
                            'dropoff_datetime': str,
                            'passenger_count': int,
                            'pickup_longitude': np.float64,
                            'pickup_latitude': np.float64,
                            'dropoff_longitude': np.float64,
                            'dropoff_latitude': np.float64,
                            'store_and_fwd_flag': str,
                            'trip_duration': int,
                        },
                        parse_dates = ['pickup_datetime', 'dropoff_datetime'],
                   )
t("Loaded {} rows data from 'train'".format(len(train)))

然后输出将如下所示:

[9.35s] Loaded 1458644 rows data from 'train'

我这样感觉有点优雅。

答案 26 :(得分:2)

我在很多地方都遇到了同样的问题,因此我创建了一个便利包horology。您可以使用pip install horology安装它,然后以一种优雅的方式完成它:

from horology import Timing

with Timing(name='Important calculations: '):
    prepare()
    do_your_stuff()
    finish_sth()

将输出:

Important calculations: 12.43 ms

或更简单(如果您有一个功能):

from horology import timed

@timed
def main():
    ...

将输出:

main: 7.12 h

它负责单位和舍入。它适用于python 3.6或更高版本。

答案 27 :(得分:1)

time.clock 已在 Python 3.3 中弃用,将从 Python 3.8 中删除:改用 time.perf_countertime.process_time

import time
start_time = time.perf_counter ()
for x in range(1, 100):
    print(x)
end_time = time.perf_counter ()
print(end_time - start_time, "seconds")

答案 28 :(得分:1)

要将metakermit's updated answer用于python 2.7,您需要monotonic包。

代码如下:

from datetime import timedelta
from monotonic import monotonic

start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))

答案 29 :(得分:0)

这是获取程序经过时间的最简单方法:-

在程序末尾编写以下代码。

import time
print(time.clock())

答案 30 :(得分:0)

您可以在Python中获得一种非常简单的方法,而无需做很多复杂的事情

import time start = time.localtime() end = time.localtime() """Total execution time in second$ """ print(end.tm_sec - start.tm_sec)

答案 31 :(得分:0)

如果要以微秒为单位测量时间,则可以使用以下版本,完全基于Paul McGuireNicojo的答案-这是Python3代码。我还添加了一些颜色:

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()=>函数,输出定时信息。

txt ==>要记录的第一个参数,它是标记计时的字符串。

atexit ==> python模块,用于注册程序退出时可以调用的函数。

答案 32 :(得分:0)

Python程序执行度量的时间可能不一致,具体取决于:

  • 可以使用不同的算法评估相同的程序
  • 算法之间的运行时间不同
  • 实施之间的运行时间不同
  • 计算机之间的运行时间不同
  • 基于小输入
  • 无法预测运行时间

这是因为最有效的方法是使用“增长顺序”并学习大“O”符号来正确地进行,https://en.wikipedia.org/wiki/Big_O_notation

无论如何,您可以尝试使用这个简单的算法评估任何Python程序在每秒特定计算机计数步骤中的性能: 使其适应您要评估的程序

import time

now = time.time()
future = now + 10
step = 4 # why 4 steps? because until here already 4 operations executed
while time.time() < future:
    step += 3 # why 3 again? because while loop execute 1 comparison and 1 plus equal statement
step += 4 # why 3 more? because 1 comparison starting while when time is over plus final assignment of step + 1 and print statement
print(str(int(step / 10)) + " steps per second")

希望这对你有所帮助。

答案 33 :(得分:0)

对于功能,我建议使用我创建的这个简单的装饰器。

def timeit(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()
        if 'log_time' in kw:
            name = kw.get('log_name', method.__name__.upper())
            kw['log_time'][name] = int((te - ts) * 1000)
        else:
            print('%r  %2.22f ms' % (method.__name__, (te - ts) * 1000))
        return result
    return timed

@timeit
def foo():
    do_some_work()


# 'foo'  0.000953 ms

答案 34 :(得分:0)

this answer之后创建了一个简单但方便的工具。

import time
from datetime import timedelta

def start_time_measure(message=None):
    if message:
        print(message)
    return time.monotonic()

def end_time_measure(start_time, print_prefix=None):
    end_time = time.monotonic()
    if print_prefix:
        print(print_prefix + str(timedelta(seconds=end_time - start_time)))
    return end_time

用法:

total_start_time = start_time_measure()    
start_time = start_time_measure('Doing something...')
# Do something
end_time_measure(start_time, 'Done in: ')
start_time = start_time_measure('Doing something else...')
# Do something else
end_time_measure(start_time, 'Done in: ')
end_time_measure(total_start_time, 'Total time: ')

输出:

Doing something...
Done in: 0:00:01.218000
Doing something else...
Done in: 0:00:01.313000
Total time: 0:00:02.672000