如何测量python中代码行之间的时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14452145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:33:02  来源:igfitidea点击:

How to measure time taken between lines of code in python?

pythontimeprofilingmeasure

提问by alvas

So in Java, we can do How to measure time taken by a function to execute

所以在 Java 中,我们可以做How to measure time 执行一个函数所花费的时间

But how is it done in python? To measure the time start and end time between lines of codes? Something that does this:

但是在python中它是如何完成的呢?测量代码行之间的时间开始和结束时间?这样做的东西:

import some_time_library

starttime = some_time_library.some_module()
code_tobe_measured() 
endtime = some_time_library.some_module()

time_taken = endtime - starttime

采纳答案by Yevgen Yampolskiy

If you want to measure CPU time, can use time.process_time()for Python 3.3 and above:

如果要测量 CPU 时间,可time.process_time()用于 Python 3.3 及以上版本:

import time
start = time.process_time()
# your code here    
print(time.process_time() - start)

First call turns the timer on, and second call tells you how many seconds have elapsed.

第一个电话打开计时器,第二个电话告诉您已经过去了多少秒。

There is also a function time.clock(), but it is deprecated since Python 3.3and will be removed in Python 3.8.

还有一个 function time.clock(),但它自 Python 3.3 起弃用,并将在 Python 3.8 中删除。

There are better profiling tools like timeitand profile, however time.process_time() will measure the CPU time and this is what you're are asking about.

有更好的分析工具,例如timeitand profile,但是 time.process_time() 将测量 CPU 时间,这就是您要问的。

If you want to measure wall clock time instead, use time.time().

如果要改为测量挂钟时间,请使用time.time().

回答by Justas

With a help of a small convenience class, you can measure time spent in indented lineslike this:

在一个小型便利类的帮助下,您可以测量在缩进行中花费的时间,如下所示:

with CodeTimer():
   line_to_measure()
   another_line()
   # etc...

Which will show the following after the indented line(s) finishes executing:

在缩进的行完成执行后将显示以下内容:

Code block took: x.xxx ms

UPDATE:You can now get the class with pip install linetimerand then from linetimer import CodeTimer. See this GitHub project.

更新:您现在可以使用pip install linetimer然后获取课程from linetimer import CodeTimer。请参阅此 GitHub 项目

The code for above class:

上述类的代码:

import timeit

class CodeTimer:
    def __init__(self, name=None):
        self.name = " '"  + name + "'" if name else ''

    def __enter__(self):
        self.start = timeit.default_timer()

    def __exit__(self, exc_type, exc_value, traceback):
        self.took = (timeit.default_timer() - self.start) * 1000.0
        print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')

You could then name the code blocksyou want to measure:

然后,您可以命名要测量的代码块

with CodeTimer('loop 1'):
   for i in range(100000):
      pass

with CodeTimer('loop 2'):
   for i in range(100000):
      pass

Code block 'loop 1' took: 4.991 ms
Code block 'loop 2' took: 3.666 ms

And nestthem:

嵌套它们:

with CodeTimer('Outer'):
   for i in range(100000):
      pass

   with CodeTimer('Inner'):
      for i in range(100000):
         pass

   for i in range(100000):
      pass

Code block 'Inner' took: 2.382 ms
Code block 'Outer' took: 10.466 ms

Regarding timeit.default_timer(), it uses the best timer based on OS and Python version, see this answer.

关于timeit.default_timer(),它使用基于 OS 和 Python 版本的最佳计时器,请参阅此答案

回答by Akshaya Natarajan

You can also use timelibrary:

您还可以使用time库:

import time

start = time.time()

# your code

# end

print(f'Time: {time.time() - start}')

回答by Sayali Sonawane

I always prefer to check time in hours, minutes and seconds (%H:%M:%S) format:

我总是喜欢以小时、分钟和秒 (%H:%M:%S) 格式检查时间:

from datetime import datetime
start = datetime.now()
# your code
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken) 

output:

输出:

Time:  0:00:00.000019

回答by Marius

I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.

我一直在寻找一种如何用最少的代码输出格式化时间的方法,所以这是我的解决方案。无论如何,许多人都使用 Pandas,因此在某些情况下,这可以避免额外的库导入。

import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)

Output:

输出:

0 days 00:05:32.541600

I would recommend using this if time precision is not the most important, otherwise use timelibrary:

如果时间精度不是最重要的,我建议使用它,否则使用time库:

%timeit pd.Timestamp.now()outputs 3.29 μs ± 214 ns per loop

%timeit pd.Timestamp.now()每个循环输出 3.29 μs ± 214 ns

%timeit time.time()outputs 154 ns ± 13.3 ns per loop

%timeit time.time()每个循环输出 154 ns ± 13.3 ns

回答by Manoj Kumar

You can try this as well:

你也可以试试这个:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0