如何在 Visual Studio 代码中查看 运行 我的程序所花费的时间?
How do I see the time it took to run my program in Visual Studio Code?
有没有办法查看脚本在 VS Code 中 execute/complete 花费了多长时间?
我正在寻找这样的消息:
Program finished in 30ms
实现此目的的最简单方法是纯粹编码时间来编程。
from time import time
start_time = time()
main() # n staffs
passed_time = time() - start_time
print(f"It took {passed_time}")
使用'time'
脚本启动时:
import time
start_time = time.time()
do something # here your actual code/routine
print("Process finished --- %s seconds ---" % (time.time() - start_time))
您可以创建一个简单的装饰器函数来为您的函数计时。
import time
def decoratortimer(decimal):
def decoratorfunction(f):
def wrap(*args, **kwargs):
time1 = time.monotonic()
result = f(*args, **kwargs)
time2 = time.monotonic()
print('{:s} function took {:.{}f} ms'.format(f.__name__, ((time2-time1)*1000.0), decimal ))
return result
return wrap
return decoratorfunction
@decoratortimer(2)
def callablefunction(name):
print(name)
print(callablefunction('John'))
我建议使用time.monotonic
(这是一个不会倒退的时钟)来提高准确性。
为了找到你的函数 运行 时间更喜欢 time.perf_counter() 而不是 time.time()。
详情见下方link
Understanding time.perf_counter() and time.process_time()
您可以使用类似这样的方法创建您自己的自定义计时器
from time import perf_counter
def f(a1,a2):
return a1 * a2
def timer(f,*args):
start = perf_counter()
f(*args)
return (1000 * (perf_counter()-start)) # this returns time in ms
a1 = np.random.rand(100)
a2 = np.random.rand(100)
np.mean([timer(f,a1,a2) for _ in range(100)]) # average out result for 100 runs
如果您使用的是 jupyter notebook,请使用以下命令
%%timeit
f(a1,a2)
有没有办法查看脚本在 VS Code 中 execute/complete 花费了多长时间?
我正在寻找这样的消息:
Program finished in 30ms
实现此目的的最简单方法是纯粹编码时间来编程。
from time import time
start_time = time()
main() # n staffs
passed_time = time() - start_time
print(f"It took {passed_time}")
使用'time'
脚本启动时:
import time
start_time = time.time()
do something # here your actual code/routine
print("Process finished --- %s seconds ---" % (time.time() - start_time))
您可以创建一个简单的装饰器函数来为您的函数计时。
import time
def decoratortimer(decimal):
def decoratorfunction(f):
def wrap(*args, **kwargs):
time1 = time.monotonic()
result = f(*args, **kwargs)
time2 = time.monotonic()
print('{:s} function took {:.{}f} ms'.format(f.__name__, ((time2-time1)*1000.0), decimal ))
return result
return wrap
return decoratorfunction
@decoratortimer(2)
def callablefunction(name):
print(name)
print(callablefunction('John'))
我建议使用time.monotonic
(这是一个不会倒退的时钟)来提高准确性。
为了找到你的函数 运行 时间更喜欢 time.perf_counter() 而不是 time.time()。 详情见下方link
Understanding time.perf_counter() and time.process_time()
您可以使用类似这样的方法创建您自己的自定义计时器
from time import perf_counter
def f(a1,a2):
return a1 * a2
def timer(f,*args):
start = perf_counter()
f(*args)
return (1000 * (perf_counter()-start)) # this returns time in ms
a1 = np.random.rand(100)
a2 = np.random.rand(100)
np.mean([timer(f,a1,a2) for _ in range(100)]) # average out result for 100 runs
如果您使用的是 jupyter notebook,请使用以下命令
%%timeit
f(a1,a2)