测量Python中经过的时间?

gil*_*rt8 1031 python performance timeit measure

我想要的是开始在我的代码中的某个地方计算时间,然后获得通过的时间,以测量执行少量功能所花费的时间.我认为我使用的是timeit模块错误,但文档对我来说只是让人困惑.

import timeit

start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 1263

如果您只想测量两点之间经过的挂钟时间,可以使用 time.time():

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)
Run Code Online (Sandbox Code Playgroud)

这给出了以秒为单位的执行时间.

3.3以后的另一个选择可能是使用perf_counterprocess_time根据您的要求.在3.3之前,建议使用time.clock(感谢Amber).但是,它目前已被弃用:

在Unix上,将当前处理器时间返回为以秒为单位的浮点数.精确度,实际上是"处理器时间"含义的定义,取决于同名C函数的精度.

在Windows上,此函数返回自第一次调用此函数以来经过的挂钟秒,作为浮点数,基于Win32函数QueryPerformanceCounter().分辨率通常优于1微秒.

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

  • (对于性能测量,`time.clock()`实际上是首选,因为如果系统时钟搞乱它就不会受到干扰,但`.time()`主要完成相同的目的.) (101认同)
  • 并且对于微秒,使用datetime.time() (14认同)
  • @Danijel:`print(timedelta(seconds = execution_time))`.虽然这是一个单独的问题. (12认同)
  • 我认为python -mtimeit更好,因为它运行更多次,它是作为一种在python中测量时间的本地方式构建的 (4认同)
  • 是否有一种很好的方法可以将产生的execturion时间在几秒钟内转换为HH:MM :: SS? (4认同)
  • time.clock() 在 Python 3.3 https://docs.python.org/3.3/library/time.html#time.clock 被弃用 (4认同)
  • time.clock() 对我不起作用。请参阅@JFSebastian 的 timeit 答案 (3认同)
  • @Amber:`time.clock()`意思(测量的是什么),它的准确度和精度(分辨率)在平台之间有所不同.[文档](https://docs.python.org/3/library/time.html#time.clock)不再推荐`time.clock()`进行基准测试.[`timeit.default_timer()`可以改为使用.](http://stackoverflow.com/a/25823885/4279) (2认同)
  • 我更喜欢这个。Timeit 文档太混乱了。`from datetime import datetime startTime= datetime.now() # 插入你的代码 timeElapsed=datetime.now()-startTime print('Time elpased (hh:mm:ss.ms) {}'.format(timeElapsed))` (2认同)
  • `time.time()` 是一个坏主意,因为系统时钟可以重置,这会让你回到过去。`time.monotonic()` 负责处理这个问题(单调=它只向前推进)。`time.perf_counter()` 也是单调的,但具有更高的精度,因此建议将其用于挂钟时间。 (2认同)

jfs*_*jfs 575

timeit.default_timer而不是timeit.timeit.前者提供了您平台上可用的最佳时钟和自动版本的Python:

from timeit import default_timer as timer

start = timer()
# ...
end = timer()
print(end - start) # Time in seconds, e.g. 5.38091952400282
Run Code Online (Sandbox Code Playgroud)

timeit.default_timer根据操作系统分配给time.time()或time.clock().关于Python 3.3+ default_timertime.perf_counter()在所有平台上.请参阅Python - time.clock()与time.time() - 准确度?

也可以看看:

  • 优秀的答案 - 使用**timeit**将产生更准确的结果,因为它会自动解决垃圾收集和操作系统差异等问题 (15认同)
  • 我认为官方文档中的这个注释需要添加`default_timer() 测量值可能会受到同一台机器上运行的其他程序的影响,因此需要准确计时的最佳做法是重复计时几次并使用最好的时间。-r 选项对此很有用;在大多数情况下,默认 3 次重复可能就足够了。在 Unix 上,您可以使用 time.clock() 来测量 CPU 时间。` (9认同)
  • @KhushbooTiwari,以秒为单位。 (3认同)

Pie*_*tti 121

仅限Python 3:

由于从Python 3.3开始不推荐使用 time.clock(),因此您需要使用time.perf_counter()系统范围的时序或time.process_time()进程范围的时序,就像您以前使用的方式一样time.clock():

import time

t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t
Run Code Online (Sandbox Code Playgroud)

新功能process_time不包括睡眠期间经过的时间.

  • [使用`timeit.default_timer`](http://stackoverflow.com/a/25823885/4279)代替`time.perf_counter`.前者将选择适当的计时器来衡量为您的平台和Python版本调整的时间性能.`process_time()`不*包括睡眠时间,因此不适合测量经过的时间. (25认同)
  • 我正在使用Pierre建议的实现,以秒为单位给出值吗? (2认同)
  • 这个答案似乎偏离主题(嗯,问题不是很具体)。有两种“时间”测量:两点之间的挂钟时间、进程的CPU消耗。 (2认同)

unu*_*tbu 78

鉴于你想要的时间,

test.py:

def foo(): 
    # print "hello"   
    return "hello"
Run Code Online (Sandbox Code Playgroud)

最简单的方法timeit是从命令行调用它:

% python -mtimeit -s'import test' 'test.foo()'
1000000 loops, best of 3: 0.254 usec per loop
Run Code Online (Sandbox Code Playgroud)

不要试图使用time.timetime.clock(天真地)比较功能的速度.他们可能会产生误导性的结果.

PS.不要将打印语句放在您想要的时间函数中; 否则测量的时间将取决于终端速度.


goj*_*omo 61

使用上下文管理器执行此操作很有趣,该上下文管理器会在进入with块时自动记住开始时间,然后在块退出时冻结结束时间.通过一些小技巧,您甚至可以从相同的上下文管理器功能获得块内运行的经过时间计数.

核心库没有这个(但可能应该).一旦到位,您可以执行以下操作:

with elapsed_timer() as elapsed:
    # some lengthy code
    print( "midpoint at %.2f seconds" % elapsed() )  # time so far
    # other lengthy code

print( "all done at %.2f seconds" % elapsed() )
Run Code Online (Sandbox Code Playgroud)

这里的contextmanager代码足以完成这个诀窍:

from contextlib import contextmanager
from timeit import default_timer

@contextmanager
def elapsed_timer():
    start = default_timer()
    elapser = lambda: default_timer() - start
    yield lambda: elapser()
    end = default_timer()
    elapser = lambda: end-start
Run Code Online (Sandbox Code Playgroud)

还有一些可运行的演示代码:

import time

with elapsed_timer() as elapsed:
    time.sleep(1)
    print(elapsed())
    time.sleep(2)
    print(elapsed())
    time.sleep(3)
Run Code Online (Sandbox Code Playgroud)

请注意,通过此函数的设计,返回值elapsed()在块退出时被冻结,并且其他调用返回相同的持续时间(在此玩具示例中约为6秒).

  • 其他上下文管理器示例:http://dabeaz.blogspot.fr/2010/02/context-manager-for-timing-benchmarks.html (2认同)

use*_*806 52

我更喜欢这个.timeitdoc太令人困惑了.

from datetime import datetime 

start_time = datetime.now() 

# INSERT YOUR CODE 

time_elapsed = datetime.now() - start_time 

print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))
Run Code Online (Sandbox Code Playgroud)

请注意,这里没有任何格式化,我只是写入hh:mm:ss打印输出,因此可以解释time_elapsed

  • 以这种方式测量经过的时间是有风险的,因为 datetime.now() 可能会因网络时间同步、夏令时切换或用户摆弄时钟等原因而在两次调用之间发生变化。 (6认同)

Gal*_*cha 43

以秒为单位的测量时间

from timeit import default_timer as timer
from datetime import timedelta

start = timer()
end = timer()
print(timedelta(seconds=end-start))
Run Code Online (Sandbox Code Playgroud)

输出

0:00:01.946339
Run Code Online (Sandbox Code Playgroud)

  • 这是最简洁的答案和最干净的输出。 (8认同)

Woj*_*ski 39

计算操作持续时间的最简单方法:

import time

start_time = time.monotonic()

<operations, programs>

print('seconds: ', time.monotonic() - start_time)
Run Code Online (Sandbox Code Playgroud)

官方文档在这里

  • 最好使用“time.monotonic_ns()”,请参阅https://docs.python.org/3/library/time.html#time.monotonic_ns (2认同)

roc*_*ker 27

使用time.time测量执行给你你的命令,包括运行其他程序在计算机上花费的时间的总执行时间.这是用户注意到的时间,但如果您想要比较不同的代码片段/算法/函数/ ...则不好

更多信息timeit:

如果您想更深入地了解分析:

更新:我在去年使用了很多http://pythonhosted.org/line_profiler/并发现它非常有用,并建议使用它代替Pythons配置文件模块.


Min*_* He 25

现在是2019年。让我们以一种简洁的方式做到这一点:

from ttictoc import TicToc
t = TicToc() ## TicToc("name")
t.tic();
# your code ...
t.toc();
print(t.elapsed)
Run Code Online (Sandbox Code Playgroud)

使用此方法而不是其他方法的优点:

  1. 简洁明了。它不需要程序员编写额外的变量,例如:
    t1 = time()
    t2 =
    经过的time()= t2-t1
  2. 带嵌套
t = TicToc(nested=True)
t.tic()
some code1...
t.tic()
some code2...
t.tic()
some code3...
print(t.toc()) # Prints time for code 3 
print(t.toc()) # Prints time for code 2 with code 3
print(t.toc()) # Prints time for code 1 with code 2 and 3
Run Code Online (Sandbox Code Playgroud)
  1. 保留井字游戏的名称。
t = TicToc("save user")
print(t.name)
Run Code Online (Sandbox Code Playgroud)

请参考此链接以获取更多详细说明。

  • 最好说明使用此库相对于其他方法的优势。 (3认同)

Dan*_*jel 19

这是一个微小的计时器类,返回"hh:mm:ss"字符串:

class Timer:
  def __init__(self):
    self.start = time.time()

  def restart(self):
    self.start = time.time()

  def get_time_hhmmss(self):
    end = time.time()
    m, s = divmod(end - self.start, 60)
    h, m = divmod(m, 60)
    time_str = "%02d:%02d:%02d" % (h, m, s)
    return time_str
Run Code Online (Sandbox Code Playgroud)

用法:

# Start timer
my_timer = Timer()

# ... do something

# Get time string:
time_hhmmss = my_timer.get_time_hhmmss()
print("Time elapsed: %s" % time_hhmmss )

# ... use the timer again
my_timer.restart()

# ... do something

# Get time:
time_hhmmss = my_timer.get_time_hhmmss()

# ... etc
Run Code Online (Sandbox Code Playgroud)


Shi*_*hah 18

这是我在这里经过许多好的答案以及其他一些文章后的发现.

首先,您总是希望使用timeit而不是time.time(并且在许多情况下是反向API)因为

  1. timeit 选择您的操作系统和Python版本上可用的最佳计时器.
  2. timeit 禁用垃圾收集,但这不是你可能想要或不想要的东西.

现在问题是timeit并不是那么简单,因为它需要设置,当你有大量的导入时,事情变得很难看.理想情况下,您只需要装饰器或使用with块并测量时间.不幸的是,没有内置的可用内容,所以我创建了下面的小实用程序模块.

定时实用程序模块

# utils.py
from functools import wraps
import gc
import timeit

def MeasureTime(f):
    @wraps(f)
    def _wrapper(*args, **kwargs):
        gcold = gc.isenabled()
        gc.disable()
        start_time = timeit.default_timer()
        try:
            result = f(*args, **kwargs)
        finally:
            elapsed = timeit.default_timer() - start_time
            if gcold:
                gc.enable()
            print('Function "{}": {}s'.format(f.__name__, elapsed))
        return result
    return _wrapper

class MeasureBlockTime:
    def __init__(self,name="(block)", no_print = False, disable_gc = True):
        self.name = name
        self.no_print = no_print
        self.disable_gc = disable_gc
    def __enter__(self):
        if self.disable_gc:
            self.gcold = gc.isenabled()
            gc.disable()
        self.start_time = timeit.default_timer()
    def __exit__(self,ty,val,tb):
        self.elapsed = timeit.default_timer() - self.start_time
        if self.disable_gc and self.gcold:
            gc.enable()
        if not self.no_print:
            print('Function "{}": {}s'.format(self.name, self.elapsed))
        return False #re-raise any exceptions
Run Code Online (Sandbox Code Playgroud)

如何计时功能

现在你可以通过在它前面放一个装饰器来计时任何功能:

import utils

@utils.MeasureTime
def MyBigFunc():
    #do something time consuming
    for i in range(10000):
        print(i)
Run Code Online (Sandbox Code Playgroud)

如何计时代码块

如果你想要对代码的一部分进行计时,那么只需将其置于with块内:

import utils

#somewhere in my code

with utils.MeasureBlockTime("MyBlock"):
    #do something time consuming
    for i in range(10000):
        print(i)

# rest of my code
Run Code Online (Sandbox Code Playgroud)

好处

有几个半支持的版本浮动,所以我想指出一些亮点:

  1. 出于前面所述的原因,使用timeit from timeit而不是time.time.
  2. 在计时期间禁用GC.
  3. Decorator接受具有命名或未命名参数的函数.
  4. 能够在块定时中禁用打印(使用with utils.MeasureBlockTime() as t然后再使用t.elapsed).
  5. 能够保持gc启用块时序.


san*_*ora 17

python cProfile和pstats模块为测量某些功能所用的时间提供了极大的支持,而无需在现有功能周围添加任何代码.

例如,如果你有一个python脚本timeFunctions.py:

import time

def hello():
    print "Hello :)"
    time.sleep(0.1)

def thankyou():
    print "Thank you!"
    time.sleep(0.05)

for idx in range(10):
    hello()

for idx in range(100):
    thankyou()
Run Code Online (Sandbox Code Playgroud)

要运行探查器并为文件生成统计信息,您只需运行:

python -m cProfile -o timeStats.profile timeFunctions.py
Run Code Online (Sandbox Code Playgroud)

这样做是使用cProfile模块分析timeFunctions.py中的所有函数并收集timeStats.profile文件中的统计信息.请注意,我们不必向现有模块添加任何代码(timeFunctions.py),这可以使用任何模块完成.

获得stats文件后,可以按如下方式运行pstats模块:

python -m pstats timeStats.profile
Run Code Online (Sandbox Code Playgroud)

这将运行交互式统计浏览器,为您提供许多不错的功能.对于您的特定用例,您只需检查您的功能的统计数据.在我们的示例中,检查两个函数的统计信息显示以下内容:

Welcome to the profile statistics browser.
timeStats.profile% stats hello
<timestamp>    timeStats.profile

         224 function calls in 6.014 seconds

   Random listing order was used
   List reduced from 6 to 1 due to restriction <'hello'>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       10    0.000    0.000    1.001    0.100 timeFunctions.py:3(hello)

timeStats.profile% stats thankyou
<timestamp>    timeStats.profile

         224 function calls in 6.014 seconds

   Random listing order was used
   List reduced from 6 to 1 due to restriction <'thankyou'>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      100    0.002    0.000    5.012    0.050 timeFunctions.py:7(thankyou)
Run Code Online (Sandbox Code Playgroud)

虚拟示例没有做太多,但让您了解可以做什么.关于这种方法最好的部分是我不必编辑任何现有代码来获取这些数字,显然有助于分析.

  • 其实有一些困惑;默认情况下,cProfile 确实会查看挂钟时间。我赞成你的回答。 (2认同)

Bri*_*rns 17

这是定时代码的另一个上下文管理器 -

用法:

from benchmark import benchmark

with benchmark("Test 1+1"):
    1+1
=>
Test 1+1 : 1.41e-06 seconds
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要时间价值

with benchmark("Test 1+1") as b:
    1+1
print(b.time)
=>
Test 1+1 : 7.05e-07 seconds
7.05233786763e-07
Run Code Online (Sandbox Code Playgroud)

benchmark.py:

from timeit import default_timer as timer

class benchmark(object):

    def __init__(self, msg, fmt="%0.3g"):
        self.msg = msg
        self.fmt = fmt

    def __enter__(self):
        self.start = timer()
        return self

    def __exit__(self, *args):
        t = timer() - self.start
        print(("%s : " + self.fmt + " seconds") % (self.msg, t))
        self.time = t
Run Code Online (Sandbox Code Playgroud)

改编自http://dabeaz.blogspot.fr/2010/02/context-manager-for-timing-benchmarks.html


Leo*_*ine 16

使用分析器模块.它给出了非常详细的概况.

import profile
profile.run('main()')
Run Code Online (Sandbox Code Playgroud)

它输出如下:

          5 function calls in 0.047 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(exec)
        1    0.047    0.047    0.047    0.047 :0(setprofile)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        0    0.000             0.000          profile:0(profiler)
        1    0.000    0.000    0.047    0.047 profile:0(main())
        1    0.000    0.000    0.000    0.000 two_sum.py:2(twoSum)
Run Code Online (Sandbox Code Playgroud)

我发现它非常有用.


Dan*_*ger 16

如果您希望能够方便地对函数进行计时,您可以使用一个简单的装饰器:

import time

def timing_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        original_return_val = func(*args, **kwargs)
        end = time.perf_counter()
        print("time elapsed in ", func.__name__, ": ", end - start, sep='')
        return original_return_val

    return wrapper
Run Code Online (Sandbox Code Playgroud)

您可以在想要计时的函数上使用它,如下所示:

@timing_decorator
def function_to_time():
    time.sleep(1)

function_to_time()
Run Code Online (Sandbox Code Playgroud)

任何时候你调用function_to_time,它都会打印花费了多长时间以及正在计时的函数的名称。


Dav*_*vid 15

我喜欢它简单(python 3):

from timeit import timeit

timeit(lambda: print("hello"))
Run Code Online (Sandbox Code Playgroud)

单个执行的输出为微秒

2.430883963010274
Run Code Online (Sandbox Code Playgroud)

说明:timeit 默认情况下执行匿名函数一百万次,结果以秒为单位。因此,单次执行的结果是相同的数量,但平均为微秒


对于缓慢的操作添加较低数量的迭代,或者你可能会永远等待:

import time

timeit(lambda: time.sleep(1.5), number=1)
Run Code Online (Sandbox Code Playgroud)

输出总是在数目迭代:

1.5015795179999714
Run Code Online (Sandbox Code Playgroud)


Eya*_* Ch 14

(仅限Ipython)您可以使用%timeit来测量平均处理时间:

def foo():
    print "hello"
Run Code Online (Sandbox Code Playgroud)

然后:

%timeit foo()
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

10000 loops, best of 3: 27 µs per loop
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,可以将标志传递给%timeit,例如-n指定代码重复的次数. (4认同)

x0s*_*x0s 14

这是一个使用以下方法的答案:

  • 一个简洁的上下文管理器来计时代码片段
  • time.perf_counter()计算时间增量。它应该是首选,因为它不可调整(系统管理员和守护程序都不能更改其值),与time.time()(参见文档)相反
import time
from collections.abc import Iterator
from contextlib import contextmanager

@contextmanager
def time_it() -> Iterator[None]:
    tic: float = time.perf_counter()
    try:
        yield
    finally:
        toc: float = time.perf_counter()
        print(f"Computation time = {1000*(toc - tic):.3f}ms")
Run Code Online (Sandbox Code Playgroud)

如何使用它的示例:

# Example: vector dot product computation
with time_it():
    A = B = range(1_000_000)
    dot = sum(a*b for a,b in zip(A,B))
# Computation time = 95.353ms
Run Code Online (Sandbox Code Playgroud)

附录

import time

# to check adjustability
assert time.get_clock_info('time').adjustable
assert time.get_clock_info('perf_counter').adjustable is False
Run Code Online (Sandbox Code Playgroud)


Dmi*_*nov 11

在python3上:

from time import sleep, perf_counter as pc
t0 = pc()
sleep(1)
print(pc()-t0)
Run Code Online (Sandbox Code Playgroud)

优雅而短暂.


raa*_*cer 9

使用timeit的另一种方法:

from timeit import timeit

def func():
    return 1 + 1

time = timeit(func, number=1)
print(time)
Run Code Online (Sandbox Code Playgroud)


And*_*man 9

这是一种超级后来的回应,但它可能是某人的目的.这是一种我认为非常干净的方法.

import time

def timed(fun, *args):
    s = time.time()
    r = fun(*args)
    print('{} execution took {} seconds.'.format(fun.__name__, time.time()-s))
    return(r)

timed(print, "Hello")
Run Code Online (Sandbox Code Playgroud)

请记住,"print"是Python 3中的一个函数,而不是Python 2.7.但是,它适用于任何其他功能.干杯!


ruo*_*ola 9

这是我用作通用实用程序的一个记录良好且类型齐全的带提示的装饰器:

from functools import wraps
from time import perf_counter
from typing import Any, Callable, Optional, TypeVar, cast

F = TypeVar("F", bound=Callable[..., Any])


def timer(prefix: Optional[str] = None, precision: int = 6) -> Callable[[F], F]:
    """Use as a decorator to time the execution of any function.

    Args:
        prefix: String to print before the time taken.
            Default is the name of the function.
        precision: How many decimals to include in the seconds value.

    Examples:
        >>> @timer()
        ... def foo(x):
        ...     return x
        >>> foo(123)
        foo: 0.000...s
        123
        >>> @timer("Time taken: ", 2)
        ... def foo(x):
        ...     return x
        >>> foo(123)
        Time taken: 0.00s
        123

    """
    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            nonlocal prefix
            prefix = prefix if prefix is not None else f"{func.__name__}: "
            start = perf_counter()
            result = func(*args, **kwargs)
            end = perf_counter()
            print(f"{prefix}{end - start:.{precision}f}s")
            return result
        return cast(F, wrapper)
    return decorator
Run Code Online (Sandbox Code Playgroud)

用法示例:

from timer import timer


@timer(precision=9)
def takes_long(x: int) -> bool:
    return x in (i for i in range(x + 1))


result = takes_long(10**8)
print(result)
Run Code Online (Sandbox Code Playgroud)

输出:

from functools import wraps
from time import perf_counter
from typing import Any, Callable, Optional, TypeVar, cast

F = TypeVar("F", bound=Callable[..., Any])


def timer(prefix: Optional[str] = None, precision: int = 6) -> Callable[[F], F]:
    """Use as a decorator to time the execution of any function.

    Args:
        prefix: String to print before the time taken.
            Default is the name of the function.
        precision: How many decimals to include in the seconds value.

    Examples:
        >>> @timer()
        ... def foo(x):
        ...     return x
        >>> foo(123)
        foo: 0.000...s
        123
        >>> @timer("Time taken: ", 2)
        ... def foo(x):
        ...     return x
        >>> foo(123)
        Time taken: 0.00s
        123

    """
    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            nonlocal prefix
            prefix = prefix if prefix is not None else f"{func.__name__}: "
            start = perf_counter()
            result = func(*args, **kwargs)
            end = perf_counter()
            print(f"{prefix}{end - start:.{precision}f}s")
            return result
        return cast(F, wrapper)
    return decorator
Run Code Online (Sandbox Code Playgroud)

可以通过以下方式检查 doctests:

$ python3 -m doctest --verbose -o=ELLIPSIS timer.py
Run Code Online (Sandbox Code Playgroud)

类型提示为:

$ mypy timer.py
Run Code Online (Sandbox Code Playgroud)


小智 7

我们还可以将时间转换为人类可读的时间.

import time, datetime

start = time.clock()

def num_multi1(max):
    result = 0
    for num in range(0, 1000):
        if (num % 3 == 0 or num % 5 == 0):
            result += num

    print "Sum is %d " % result

num_multi1(1000)

end = time.clock()
value = end - start
timestamp = datetime.datetime.fromtimestamp(value)
print timestamp.strftime('%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)


Woj*_*ski 7

如何测量两次操作之间的时间。比较两次操作的时间。

import time

b = (123*321)*123
t1 = time.time()

c = ((9999^123)*321)^123
t2 = time.time()

print(t2-t1)
Run Code Online (Sandbox Code Playgroud)

7.987022399902344e-05


Mye*_*Joo 7

print_elapsed_time 函数如下

def print_elapsed_time(prefix=''):
    e_time = time.time()
    if not hasattr(print_elapsed_time, 's_time'):
        print_elapsed_time.s_time = e_time
    else:
        print(f'{prefix} elapsed time: {e_time - print_elapsed_time.s_time:.2f} sec')
        print_elapsed_time.s_time = e_time
Run Code Online (Sandbox Code Playgroud)

以这种方式使用它

print_elapsed_time()
.... heavy jobs ...
print_elapsed_time('after heavy jobs')
.... tons of jobs ...
print_elapsed_time('after tons of jobs')
Run Code Online (Sandbox Code Playgroud)

结果是

after heavy jobs elapsed time: 0.39 sec
after tons of jobs elapsed time: 0.60 sec  
Run Code Online (Sandbox Code Playgroud)

这个功能的优缺点是你不需要传递开始时间


Kar*_*arl 6

我为此创建了一个库,如果你想测量一个函数你就可以这样做


from pythonbenchmark import compare, measure
import time

a,b,c,d,e = 10,10,10,10,10
something = [a,b,c,d,e]

@measure
def myFunction(something):
    time.sleep(0.4)

@measure
def myOptimizedFunction(something):
    time.sleep(0.2)

myFunction(input)
myOptimizedFunction(input)
Run Code Online (Sandbox Code Playgroud)

https://github.com/Karlheinzniebuhr/pythonbenchmark


Vla*_*den 6

您可以使用timeit。

这是一个有关如何使用Python REPL测试带参数的naive_func的示例:

>>> import timeit                                                                                         

>>> def naive_func(x):                                                                                    
...     a = 0                                                                                             
...     for i in range(a):                                                                                
...         a += i                                                                                        
...     return a                                                                                          

>>> def wrapper(func, *args, **kwargs):                                                                   
...     def wrapper():                                                                                    
...         return func(*args, **kwargs)                                                                  
...     return wrapper                                                                                    

>>> wrapped = wrapper(naive_func, 1_000)                                                                  

>>> timeit.timeit(wrapped, number=1_000_000)                                                              
0.4458435332577161  
Run Code Online (Sandbox Code Playgroud)

如果function没有任何参数,则不需要包装函数。


Lee*_*ton 6

尽管在问题中没有严格要求,但通常情况下,您需要一种简单、统一的方法来增量地测量几行代码之间经过的时间。

如果您使用的是 Python 3.8 或更高版本,您可以使用赋值表达式(也称为 walrus 运算符)以一种相当优雅的方式实现这一点:

import time

start, times = time.perf_counter(), {}

print("hello")
times["print"] = -start + (start := time.perf_counter())

time.sleep(1.42)
times["sleep"] = -start + (start := time.perf_counter())

a = [n**2 for n in range(10000)]
times["pow"] = -start + (start := time.perf_counter())

print(times)
Run Code Online (Sandbox Code Playgroud)

=>

{'print': 2.193450927734375e-05, 'sleep': 1.4210970401763916, 'power': 0.005671024322509766}
Run Code Online (Sandbox Code Playgroud)


Gui*_*ier 5

要了解每个函数的递归调用,请执行以下操作:

%load_ext snakeviz
%%snakeviz
Run Code Online (Sandbox Code Playgroud)

它只需在Jupyter笔记本中使用这两行代码,并生成一个漂亮的交互式图表。例如:

在此处输入图片说明

这是代码。再次,以2开头的%行是使用snakeviz所需的仅有的额外代码行:

# !pip install snakeviz
%load_ext snakeviz
import glob
import hashlib

%%snakeviz

files = glob.glob('*.txt')
def print_files_hashed(files):
    for file in files:
        with open(file) as f:
            print(hashlib.md5(f.read().encode('utf-8')).hexdigest())
print_files_hashed(files)
Run Code Online (Sandbox Code Playgroud)

在笔记本外运行snakeviz也似乎是可能的。在snakeviz网站上有更多信息。


Acu*_*nus 5

这种独特的基于类的方法提供了可打印的字符串表示、可定制的舍入以及以字符串或浮点数形式方便地访问经过的时间。它是用Python 3.7开发的。

import datetime
import timeit


class Timer:
    """Measure time used."""
    # Ref: https://stackoverflow.com/a/57931660/

    def __init__(self, round_ndigits: int = 0):
        self._round_ndigits = round_ndigits
        self._start_time = timeit.default_timer()

    def __call__(self) -> float:
        return timeit.default_timer() - self._start_time

    def __str__(self) -> str:
        return str(datetime.timedelta(seconds=round(self(), self._round_ndigits)))
Run Code Online (Sandbox Code Playgroud)

用法:

# Setup timer
>>> timer = Timer()

# Access as a string
>>> print(f'Time elapsed is {timer}.')
Time elapsed is 0:00:03.
>>> print(f'Time elapsed is {timer}.')
Time elapsed is 0:00:04.

# Access as a float
>>> timer()
6.841332235
>>> timer()
7.970274425
Run Code Online (Sandbox Code Playgroud)


ing*_*ere 5

作为 lambda,获取经过的时间和时间戳:

import datetime
t_set = lambda: datetime.datetime.now().astimezone().replace(microsecond=0)
t_diff = lambda t: str(t_set() - t)
t_stamp = lambda t=None: str(t) if t else str(t_set())
Run Code Online (Sandbox Code Playgroud)

在实践中:

>>> 
>>> t_set()
datetime.datetime(2021, 3, 21, 1, 25, 17, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200), 'PDT'))
>>> t = t_set()
>>> t_diff(t)
'0:00:14'
>>> t_diff(t)
'0:00:23'
>>> t_stamp()
'2021-03-21 01:25:57-07:00'
>>> t_stamp(t)
'2021-03-21 01:25:22-07:00'
>>> 
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

1162897 次

最近记录:

5 年,11 月 前