我有一个 Python 命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过这个timeit
模块,但它似乎只适用于一小段代码。我想为整个节目计时。
我有一个 Python 命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过这个timeit
模块,但它似乎只适用于一小段代码。我想为整个节目计时。
Python中最简单的方法:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
这假设您的程序至少需要十分之一秒才能运行。
印刷:
--- 0.764891862869 seconds ---
我把这个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 形式。)
在 Linux 或 Unix 中:
$ time python yourprogram.py
在 Windows 中,请参阅 StackOverflow 问题:如何测量 Windows 命令行上命令的执行时间?
要获得更详细的输出,
$ time -v python yourprogram.py
Command being timed: "python3 yourprogram.py"
User time (seconds): 0.08
System time (seconds): 0.02
Percent of CPU this job got: 98%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.10
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): 9480
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 1114
Voluntary context switches: 0
Involuntary context switches: 22
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
我喜欢datetime
模块提供的输出,其中时间增量对象以人类可读的方式根据需要显示天、小时、分钟等。
例如:
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
正如 JF Sebastian 所提到的,这种方法可能会遇到一些本地时间的棘手情况,因此使用起来更安全:
import time
from datetime import timedelta
start_time = time.monotonic()
end_time = time.monotonic()
print(timedelta(seconds=end_time - start_time))
import time
start_time = time.clock()
main()
print(time.clock() - start_time, "seconds")
time.clock()
返回处理器时间,它允许我们仅计算此进程使用的时间(无论如何在 Unix 上)。文档说“无论如何,这是用于对 Python 或计时算法进行基准测试的函数”
我真的很喜欢Paul McGuire 的回答,但我使用 Python 3。所以对于那些感兴趣的人:这是他的回答的修改,适用于 *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")
如果你觉得这很有用,你仍然应该投票给他的答案而不是这个答案,因为他做了大部分工作;)。
您可以使用 Python 分析器 cProfile 来测量CPU 时间以及每个函数内部花费的时间以及每个函数被调用的次数。如果您想在不知道从哪里开始的情况下提高脚本的性能,这将非常有用。这个对另一个 Stack Overflow 问题的回答非常好。看看文档总是好的。
以下是如何从命令行使用 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}
只需使用该timeit
模块。它适用于 Python 2 和 Python 3。
import timeit
start = timeit.default_timer()
# All the program statements
stop = timeit.default_timer()
execution_time = stop - start
print("Program Executed in "+str(execution_time)) # It returns time in seconds
它会在几秒钟内返回,您可以获得执行时间。这很简单,但是您应该将这些写在启动程序执行的 w main 函数中。如果即使遇到错误也想获得执行时间,那么将参数“Start”带到它并在那里计算如下:
def sample_function(start,**kwargs):
try:
# Your statements
except:
# except statements run when your statements raise an exception
stop = timeit.default_timer()
execution_time = stop - start
print("Program executed in " + str(execution_time))
时间.时钟()
3.3 版后已弃用:此函数的行为取决于平台:根据您的要求使用perf_counter()或process_time()来获得明确定义的行为。
time.perf_counter()
返回性能计数器的值(以秒为单位),即具有最高可用分辨率的时钟以测量短持续时间。它确实包括睡眠期间经过的时间,并且是系统范围的。
time.process_time()
返回当前进程的系统和用户 CPU 时间之和的值(以秒为单位)。它不包括睡眠期间经过的时间。
start = time.process_time()
... do something
elapsed = (time.process_time() - start)
更适合 Linux:time
$ 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
在一个单元格中,您可以使用 Jupyter 的%%time
魔法命令来测量执行时间:
%%time
[ x**2 for x in range(10000)]
CPU times: user 4.54 ms, sys: 0 ns, total: 4.54 ms
Wall time: 4.12 ms
这只会捕获特定单元格的执行时间。如果您想捕获整个笔记本(即程序)的执行时间,您可以在同一目录中创建一个新笔记本并在新笔记本中执行所有单元格:
假设上面的笔记本叫做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 timings (estimated):
User : 0.00 s.
System : 0.00 s.
Wall time: 0.00 s.
以下代码段以一种很好的人类可读<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)
与@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
time.clock
已在 Python 3.3 中弃用,将从 Python 3.8 中删除:使用time.perf_counter
ortime.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")
我查看了 timeit 模块,但它似乎只适用于一小段代码。我想为整个节目计时。
$ python -mtimeit -n1 -r1 -t -s "from your_module import main" "main()"
它运行一次函数并使用函数作为计时器your_module.main()
打印经过的时间。time.time()
要在 Python 中进行模拟/usr/bin/time
,请参阅带有 /usr/bin/time 的 Python 子进程:如何捕获计时信息但忽略所有其他输出?.
time.sleep()
要测量每个函数的CPU 时间(例如,不包括 time during ),您可以使用profile
模块(cProfile
在 Python 2 上):
$ python3 -mprofile your_module.py
如果您想使用与模块相同的计时器,您可以传递-p
给上面的命令。timeit
profile
我在很多地方都遇到了同样的问题,所以我创建了一个便利包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 或更高版本。
我也喜欢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))
在IPython中,“timeit”任何脚本:
def foo():
%run bar.py
timeit foo()
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)
我使用了一个非常简单的函数来计时部分代码执行:
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'
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))]
我尝试使用以下脚本找到时差。
import time
start_time = time.perf_counter()
[main code here]
print (time.perf_counter() - start_time, "seconds")
对于函数,我建议使用我创建的这个简单的装饰器。
def timeit(method):
def timed(*args, **kwargs):
ts = time.time()
result = method(*args, **kwargs)
te = time.time()
if 'log_time' in kwargs:
name = kwargs.get('log_name', method.__name__.upper())
kwargs['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()
# 'foo' 0.000953 ms
Timeit 是 Python 中的一个类,用于计算小块代码的执行时间。
Default_timer 是此类中的一个方法,用于测量挂钟时间,而不是 CPU 执行时间。因此,其他进程执行可能会干扰这一点。因此,它对于小代码块很有用。
代码示例如下:
from timeit import default_timer as timer
start= timer()
# Some logic
end = timer()
print("Time taken:", end-start)
您只需在 Python 中执行此操作。没有必要让它变得复杂。
import time
start = time.localtime()
end = time.localtime()
"""Total execution time in minutes$ """
print(end.tm_min - start.tm_min)
"""Total execution time in seconds$ """
print(end.tm_sec - start.tm_sec)
首先,通过以管理员身份打开命令提示符 (CMD) 来
安装人性化软件包,然后在此处键入 -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))
输出:
有一个timeit
模块可用于计时 Python 代码的执行时间。
它在 Python 文档26.6 中有详细的文档和示例。timeit - 测量小代码片段的执行时间。
这是对我有用的 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()
导入文件后从您的程序调用。
Python 程序执行度量的时间可能不一致,具体取决于:
这是因为最有效的方法是使用“增长顺序”并学习大“O”符号来正确地做到这一点。
无论如何,您可以尝试使用这个简单的算法来评估任何 Python 程序在每秒特定机器计数步骤中的性能: 将其调整为您要评估的程序
import time
now = time.time()
future = now + 10
step = 4 # Why 4 steps? Because until here already four operations executed
while time.time() < future:
step += 3 # Why 3 again? Because a while loop executes one comparison and one plus equal statement
step += 4 # Why 3 more? Because one comparison starting while when time is over plus the final assignment of step + 1 and print statement
print(str(int(step / 10)) + " steps per second")
按照这个答案创建了一个简单但方便的工具。
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
这是获取程序运行时间的最简单方法:
在程序的最后写下下面的代码。
import time
print(time.clock())
要使用metakermit对 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))
如果您想以微秒为单位测量时间,那么您可以使用以下版本,完全基于Paul McGuire和Nicojo的答案——它是 Python 3 代码。我还为它添加了一些颜色:
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 模块,用于注册程序退出时可以调用的函数。
我定义了以下 Python 装饰器:
def profile(fct):
def wrapper(*args, **kw):
start_time = time.time()
ret = fct(*args, **kw)
print("{} {} {} return {} in {} seconds".format(args[0].__class__.__name__,
args[0].__class__.__module__,
fct.__name__,
ret,
time.time() - start_time))
return ret
return wrapper
并将其用于函数或类/方法:
@profile
def main()
...