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_counter或process_time根据您的要求.在3.3之前,建议使用time.clock(感谢Amber).但是,它目前已被弃用:
在Unix上,将当前处理器时间返回为以秒为单位的浮点数.精确度,实际上是"处理器时间"含义的定义,取决于同名C函数的精度.
在Windows上,此函数返回自第一次调用此函数以来经过的挂钟秒,作为浮点数,基于Win32函数
QueryPerformanceCounter().分辨率通常优于1微秒.从版本3.3开始不推荐使用:此功能的行为取决于平台:根据您的要求,使用
perf_counter()或process_time()代替具有明确定义的行为.
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_timer是time.perf_counter()在所有平台上.请参阅Python - time.clock()与time.time() - 准确度?
也可以看看:
Pie*_*tti 121
由于从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不包括睡眠期间经过的时间.
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.time或time.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秒).
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
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)
Woj*_*ski 39
计算操作持续时间的最简单方法:
import time
start_time = time.monotonic()
<operations, programs>
print('seconds: ', time.monotonic() - start_time)
Run Code Online (Sandbox Code Playgroud)
官方文档在这里。
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)
使用此方法而不是其他方法的优点:
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)
t = TicToc("save user")
print(t.name)
Run Code Online (Sandbox Code Playgroud)
请参考此链接以获取更多详细说明。
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)因为
timeit 选择您的操作系统和Python版本上可用的最佳计时器. 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)
好处
有几个半支持的版本浮动,所以我想指出一些亮点:
with utils.MeasureBlockTime() as t然后再使用t.elapsed).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)
虚拟示例没有做太多,但让您了解可以做什么.关于这种方法最好的部分是我不必编辑任何现有代码来获取这些数字,显然有助于分析.
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)
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)
优雅而短暂.
使用timeit的另一种方法:
from timeit import timeit
def func():
return 1 + 1
time = timeit(func, number=1)
print(time)
Run Code Online (Sandbox Code Playgroud)
这是一种超级后来的回应,但它可能是某人的目的.这是一种我认为非常干净的方法.
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.但是,它适用于任何其他功能.干杯!
这是我用作通用实用程序的一个记录良好且类型齐全的带提示的装饰器:
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)
输出:
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
可以通过以下方式检查 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)
如何测量两次操作之间的时间。比较两次操作的时间。
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
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)
这个功能的优缺点是你不需要传递开始时间
我为此创建了一个库,如果你想测量一个函数你就可以这样做
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
您可以使用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没有任何参数,则不需要包装函数。
尽管在问题中没有严格要求,但通常情况下,您需要一种简单、统一的方法来增量地测量几行代码之间经过的时间。
如果您使用的是 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)
%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网站上有更多信息。
这种独特的基于类的方法提供了可打印的字符串表示、可定制的舍入以及以字符串或浮点数形式方便地访问经过的时间。它是用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)
作为 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 次 |
| 最近记录: |