如何查看在 Visual Studio Code 中运行程序所花费的时间?

问题描述 投票:0回答:5

有没有办法查看 VS Code 中脚本执行/完成所需的时间?

我正在寻找类似以下的消息:

Program finished in 30ms
python visual-studio-code compiler-optimization
5个回答
11
投票

使用“时间”

当你的脚本开始时:

import time
start_time = time.time()

do something # here your actual code/routine

print("Process finished --- %s seconds ---" % (time.time() - start_time))

4
投票

您可以创建一个简单的装饰器函数来为您的函数计时。

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
(这是一个不会倒退的时钟)来提高准确性。


2
投票

实现这一目标的最简单方法是纯粹对编程时间进行编码。

perf_counter
提供
time
功能的最高准确度。

from time import perf_counter, sleep
def main():
    sleep(5)

start_time = perf_counter()

main() # Function to measure

passed_time = perf_counter() - start_time

print(f"It took {passed_time}") # It took 5.007398507999824

1
投票

为了查找函数运行时间,优先选择 time.perf_counter() 而不是 time.time()。 详情请参阅以下链接

了解 time.perf_counter() 和 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 笔记本,请使用以下内容

%%timeit
f(a1,a2)

0
投票

VS Code 刚刚发布了此功能 https://code.visualstudio.com/updates/v1_87#_command-duration-tracked

我将 https://ohmyz.sh/https://github.com/romkatv/powerlevel10k 主题一起使用,它会为您提供在 x 秒内运行的每个命令的持续时间,其中 X 设置为 〜/.p10k.zsh 经过 POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD。

但我无法让 VS Code 功能在我的设置上运行。可能与https://github.com/microsoft/vscode/issues/146587

有关
© www.soinside.com 2019 - 2024. All rights reserved.