根据对sleep()函数的重复调用,给定的代码执行所需的最短时间是多少?

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

Based on repeated calls to the sleep() function, what is the minimum amount of time that the given code will require to execute?

问题

  1. 我试图解决两个问题 - 首先,我想知道以下代码在重复调用 sleep() 函数的情况下执行所需的最短时间。我给出的代码是:
  2. ```python
  3. from tkinter import *
  4. from time import *
  5. root = Tk()
  6. canvas = Canvas(root, width=600, height=400)
  7. canvas.pack()
  8. a = canvas.create_line(10, 50, 20, 60, fill="#0000AA", width=2)
  9. for i in range (0, 500):
  10. canvas.move(a, 1, 0.2)
  11. root.update()
  12. sleep(0.02)

起初我以为也许是 0.02,但这个答案似乎太明显了,并且没有考虑到循环。所以我有点困惑。

另外,为什么上述代码的实际执行时间会比根据 sleep() 函数调用计算出的时间更长呢?

  1. <details>
  2. <summary>英文:</summary>
  3. I am trying to figure out 2 questions- Firstly, I would like to know the minimum amount of time that the following code will require to execute, given the repeated calls to the sleep() function. My given code is:

from tkinter import *
from time import *
root = Tk()
canvas = Canvas(root, width=600, height=400)
canvas.pack()

a = canvas.create_line(10, 50, 20, 60, fill="#0000AA", width=2)
for i in range (0, 500):
canvas.move(a, 1, 0.2)
root.update()
sleep(0.02)

  1. At first I thought maybe it was 0.02, but that answer seems blatantly obvious and does not take into mind the loop. So I am a bit confused.
  2. Also, why is it that the actual execution of the above code will take longer than the time calculated according to the calls to the sleep() function?
  3. </details>
  4. # 答案1
  5. **得分**: 1
  6. 所以休眠会占用 10 秒(500 * 0.02),而其他调用 `canvas.move()` `root.update()` 都会花费一些时间。可能不会太多,再加上一秒左右。
  7. 最简单的方法就是通过在你的代码周围加上一些计时代码来计算整个过程的时间:
  8. ```python
  9. import datetime
  10. start = datetime.datetime.now()
  11. # 你的代码放在这里
  12. end = datetime.datetime.now()
  13. print(end-start)
英文:

So the sleep is going to consume 10 seconds (500 * 0.02) and the other calls canvas.move() and root.update() both are going to take some time. Probably not a ton, another second or so.

The easiest thing to do is just time the whole thing by wrapping your code in some timing code:

  1. import datetime
  2. start = datetime.datetime.now()
  3. # your code here
  4. end = datetime.datetime.now()
  5. print(end-start)
  6. </details>

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

发表评论

匿名网友

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

确定