有没有一个函数可以查看脚本运行的时间?

huangapple go评论74阅读模式
英文:

Is there a function to see how long a script takes to run?

问题

我有一个可以对文件进行排序的Python脚本,我想知道它运行需要多长时间。

我搜索了一个名为"time"的模块,但它不起作用,并要求我提供实际时间。

英文:

I have a python script than can sort files and i want to know how long it takes to run.

i searched for a module that's names time but it didnt work and it asked me to put a real time.

答案1

得分: 0

你可以像这样计算执行时间:

import time

start_time = time.time()

# 在这里放入你的脚本

end_time = time.time()
execution_time = end_time - start_time

print("执行时间:", execution_time, "秒")
英文:

You can calculate execution time like that:

import time

start_time = time.time()

# your script here

end_time = time.time()
execution_time = end_time - start_time

print("Execution time:", execution_time, "seconds")

答案2

得分: 0

I prefer to use time.perf_counter() if we are talking about timing code:

from time import perf_counter

# 获取开始时间
t1 = perf_counter()

# 一些复杂耗时的函数
for i in range(10**9):
    pass

# 获取结束时间
t2 = perf_counter()

# 现在你可以从结束时间减去开始时间,得到经过的时间:
print("经过的时间:", t2 - t1)

查看文档链接:https://docs.python.org/3/library/time.html#time.perf_counter

英文:

I prefer to use time.perf_counter() if we are talking about timing code:

from time import perf_counter

# Get the start 'time'
t1 = perf_counter()

# Some complex time-consuming function
for i in range(10**9):
    pass

# Get the end 'time'
t2 = perf_counter()

# Now you subtract the start time from the end time and you have your elapsed time:
print("Elapsed time:",t2-t1)

Check the documentation here: https://docs.python.org/3/library/time.html#time.perf_counter

huangapple
  • 本文由 发表于 2023年2月24日 16:42:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定