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

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

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

问题

我试图解决两个问题 - 首先,我想知道以下代码在重复调用 sleep() 函数的情况下执行所需的最短时间。我给出的代码是:

```python
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)

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

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


<details>
<summary>英文:</summary>

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)


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. 

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? 

</details>


# 答案1
**得分**: 1

所以休眠会占用 10 秒(500 * 0.02),而其他调用 `canvas.move()` 和 `root.update()` 都会花费一些时间。可能不会太多,再加上一秒左右。

最简单的方法就是通过在你的代码周围加上一些计时代码来计算整个过程的时间:

```python
import datetime 

start = datetime.datetime.now()
# 你的代码放在这里
end = datetime.datetime.now() 

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:

import datetime 

start = datetime.datetime.now()
# your code here 
end = datetime.datetime.now() 

print(end-start)  

</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:

确定