英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论