我有一个用Python编写的命令行程序,运行时间比较长。我想知道它完成运行所需的精确时间。
我查看了timeit
模块,但是它似乎只适用于小片段的代码。我想计时整个程序的运行时间。
我有一个用Python编写的命令行程序,运行时间比较长。我想知道它完成运行所需的精确时间。
我查看了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()
。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
print(time.clock())
from datetime import timedelta
from monotonic import monotonic
start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))
from time import perf_counter, sleep
_, _, exec_time = (s := perf_counter()), sleep(1), perf_counter()-s
print(exec_time)
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 ==> log 的第一个参数,用于标记时间的字符串。
atexit ==> Python 模块,用于注册在程序退出时可以调用的函数。
在寻找两种不同方法计算所有小于等于某个数字的质数的运行时间时,我遇到了一个问题。当程序中输入用户输入时。
错误的方法
#Sample input for a number 20
#Sample output [2, 3, 5, 7, 11, 13, 17, 19]
#Total Running time = 0.634 seconds
import time
start_time = time.time()
#Method 1 to find all the prime numbers <= a Number
# Function to check whether a number is prime or not.
def prime_no(num):
if num<2:
return False
else:
for i in range(2, num//2+1):
if num % i == 0:
return False
return True
#To print all the values <= n
def Prime_under_num(n):
a = [2]
if n <2:
print("None")
elif n==2:
print(2)
else:
"Neglecting all even numbers as even numbers won't be prime in order to reduce the time complexity."
for i in range(3, n+1, 2):
if prime_no(i):
a.append(i)
print(a)
"When Method 1 is only used outputs of running time for different inputs"
#Total Running time = 2.73761 seconds #n = 100
#Total Running time = 3.14781 seconds #n = 1000
#Total Running time = 8.69278 seconds #n = 10000
#Total Running time = 18.73701 seconds #n = 100000
#Method 2 to find all the prime numbers <= a Number
def Prime_under_num(n):
a = [2]
if n <2:
print("None")
elif n==2:
print(2)
else:
for i in range(3, n+1, 2):
if n%i ==0:
pass
else:
a.append(i)
print(a)
"When Method 2 is only used outputs of running time for different inputs"
# Total Running time = 2.75935 seconds #n = 100
# Total Running time = 2.86332 seconds #n = 1000
# Total Running time = 4.59884 seconds #n = 10000
# Total Running time = 8.55057 seconds #n = 100000
if __name__ == "__main__" :
n = int(input())
Prime_under_num(n)
print("Total Running time = {:.5f} seconds".format(time.time() - start_time))
if __name__ == "__main__" :
n = int(input())
start_time = time.time()
Prime_under_num(n)
print("Total Running time = {:.3f} seconds".format(time.time() - start_time))
因此,当单独使用这两种方法时,每种方法的输出如下:
# Method 1
# Total Running time = 0.00159 seconds #n = 100
# Total Running time = 0.00506 seconds #n = 1000
# Total Running time = 0.22987 seconds #n = 10000
# Total Running time = 18.55819 seconds #n = 100000
# Method 2
# Total Running time = 0.00011 seconds #n = 100
# Total Running time = 0.00118 seconds #n = 1000
# Total Running time = 0.00302 seconds #n = 10000
# Total Running time = 0.01450 seconds #n = 100000
默认情况下,Linux或Unix系统(在macOS上测试过)在终端上带有time
命令,您可以使用它来运行Python脚本并获取运行脚本的real
、user
、sys
时间信息。
然而,默认输出并不是很清晰(至少对我来说),而且默认的time
命令甚至不接受任何选项作为参数来格式化输出。这是因为有两个版本的time
- 一个内置于bash中,提供最小版本,另一个位于/usr/bin/time
。
/usr/bin/time
命令接受额外的参数,如 -al
、-h
、-p
和 -o
。我最喜欢的是 -p
,它可以将输出显示在新行中,如下所示:
real 2.18
user 17.92
sys 2.71
time
是 Unix 系统特定的。这意味着它是 Linux 或 macOS 终端命令。 - Md Mazedul Islam Khandef 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()
...