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

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

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

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

  1. import time
  2. start_time = time.time()
  3. # 在这里放入你的脚本
  4. end_time = time.time()
  5. execution_time = end_time - start_time
  6. print("执行时间:", execution_time, "秒")
英文:

You can calculate execution time like that:

  1. import time
  2. start_time = time.time()
  3. # your script here
  4. end_time = time.time()
  5. execution_time = end_time - start_time
  6. print("Execution time:", execution_time, "seconds")

答案2

得分: 0

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

  1. from time import perf_counter
  2. # 获取开始时间
  3. t1 = perf_counter()
  4. # 一些复杂耗时的函数
  5. for i in range(10**9):
  6. pass
  7. # 获取结束时间
  8. t2 = perf_counter()
  9. # 现在你可以从结束时间减去开始时间,得到经过的时间:
  10. 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:

  1. from time import perf_counter
  2. # Get the start 'time'
  3. t1 = perf_counter()
  4. # Some complex time-consuming function
  5. for i in range(10**9):
  6. pass
  7. # Get the end 'time'
  8. t2 = perf_counter()
  9. # Now you subtract the start time from the end time and you have your elapsed time:
  10. 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:

确定