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

因此,在Java中,我们可以执行如何测量函数执行所需的时间

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

import some_time_library

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

time_taken = endtime - starttime

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

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

import some_time_library

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

time_taken = endtime - starttime

回答 0

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

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

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

还有一个功能time.clock(),但是自Python 3.3起不推荐使用,并将在Python 3.8中删除。

有更好的性能分析工具,例如timeitprofile,但是time.process_time()将测量CPU时间,这就是您要的内容。

如果您想测量挂钟时间,请使用time.time()

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

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.3 and will be removed in Python 3.8.

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

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


回答 1

您还可以使用time库:

import time

start = time.time()

# your code

# end

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

You can also use time library:

import time

start = time.time()

# your code

# end

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

回答 2

借助小型便利类,您可以像这样测量缩进行中所花费的时间

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

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

Code block took: x.xxx ms

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

以上类的代码:

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')

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

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

嵌套它们:

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

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

With a help of a small convenience class, you can measure time spent in indented lines like 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 linetimer and then from linetimer import CodeTimer. See this GitHub project.

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 blocks you 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 nest them:

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.


回答 3

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

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

输出:

Time:  0:00:00.000019

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

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

回答 4

我一直在寻找一种以最少的代码输出格式化时间的方法,因此这是我的解决方案。无论如何,许多人都使用熊猫,因此在某些情况下,可以从其他库导入中节省下来。

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

输出:

0 days 00:05:32.541600

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

%timeit pd.Timestamp.now() 每个回路输出3.29 µs±214 ns

%timeit time.time() 每个回路输出154 ns±13.3 ns

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.

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 time library:

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

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


回答 5

将代码放入函数中,然后使用装饰器进行计时是另一种选择。()此方法的优点是您只需定义一次计时器,并将其与每个功能的附加简单行一起使用。

首先,定义timer装饰器:

import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        value = func(*args, **kwargs)
        end_time = time.perf_counter()
        run_time = end_time - start_time
        print("Finished {} in {} secs".format(repr(func.__name__), round(run_time, 3)))
        return value

    return wrapper

然后,在定义函数时使用装饰器:

@timer
def doubled_and_add(num):
    res = sum([i*2 for i in range(num)])
    print("Result : {}".format(res))

我们试试吧:

doubled_and_add(100000)
doubled_and_add(1000000)

输出:

Result : 9999900000
Finished 'doubled_and_add' in 0.0119 secs
Result : 999999000000
Finished 'doubled_and_add' in 0.0897 secs

注意:我不确定为什么要使用time.perf_counter而不是time.time。欢迎发表评论。

Putting the code in a function, then using a decorator for timing is another option. (Source) The advantage of this method is that you define timer once and use it with a simple additional line for every function.

First, define timer decorator:

import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        value = func(*args, **kwargs)
        end_time = time.perf_counter()
        run_time = end_time - start_time
        print("Finished {} in {} secs".format(repr(func.__name__), round(run_time, 3)))
        return value

    return wrapper

Then, use the decorator while defining the function:

@timer
def doubled_and_add(num):
    res = sum([i*2 for i in range(num)])
    print("Result : {}".format(res))

Let’s try:

doubled_and_add(100000)
doubled_and_add(1000000)

Output:

Result : 9999900000
Finished 'doubled_and_add' in 0.0119 secs
Result : 999999000000
Finished 'doubled_and_add' in 0.0897 secs

Note: I’m not sure why to use time.perf_counter instead of time.time. Comments are welcome.


回答 6

您也可以尝试以下方法:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0

You can try this as well:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。