我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。

我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。


当前回答

time.clock在Python 3.3中已被弃用,并将从Python 3.8中删除:请改用time.perf_counter或time.prrocess_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")

其他回答

首先,以管理员身份打开命令提示符(CMD)并在那里键入,安装人性化的软件包-pip安装人性化

代码:

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

输出:

import time

start_time = time.clock()
main()
print(time.clock() - start_time, "seconds")

time.clock()返回处理器时间,它允许我们仅计算此进程使用的时间(无论如何,在Unix上)。文档中说“无论如何,这是用于Python基准测试或计时算法的函数”

我喜欢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

or

Duration: 1 day, 1:51:24.269711

正如J.F.Sebastian所提到的,这种方法在当地时间可能会遇到一些棘手的情况,因此使用更安全:

import time
from datetime import timedelta
start_time = time.monotonic()
end_time = time.monotonic()
print(timedelta(seconds=end_time - start_time))

我认为这是最好和最简单的方法:

from time import monotonic

start_time = monotonic()
# something
print(f"Run time {monotonic() - start_time} seconds")

或与装饰师一起:

from time import monotonic
    
def record_time(function):
    def wrap(*args, **kwargs):
        start_time = monotonic()
        function_return = function(*args, **kwargs)
        print(f"Run time {monotonic() - start_time} seconds")
        return function_return
    return wrap

@record_time
def your_function():
    # something

time.clock在Python 3.3中已被弃用,并将从Python 3.8中删除:请改用time.perf_counter或time.prrocess_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")