c语言延迟函数sleep
There are times when you want your program to run immediately. But there are also some times when you want to delay the execution of certain pieces of code.
有时您希望程序立即运行。 但是有时您也想延迟某些代码的执行。
That's where Python's time
module comes in. time
is part of Python's standard library, and contains the helpful sleep()
function that suspends or pauses a program for a given number of seconds:
这就是Python的time
模块的用武之地。 time
是Python的标准库的一部分,并包含有帮助sleep()
函数,暂停或暂停节目的几秒钟内给定数量:
import time
print('runs immediately')
for letter in 'hello, world!':
time.sleep(2) # sleep 2 seconds between each print
print(letter)
Output:
输出:
runs immediately
h # each character printed after a two second delay
e
l
l
o
,
w
o
r
l
d
!
Floating point numbers can be given as the argument to sleep()
for more precise sleep times. For example, the following code will delay each print()
statement for half a second, or 500 ms:
可以将浮点数作为sleep()
的参数来获得更精确的睡眠时间。 例如,以下代码将每个print()
语句延迟半秒或500毫秒:
import time
for letter in 'floats work, too':
time.sleep(0.5) # adds a 500 ms delay
print(letter)
Output:
输出:
f # each character printed after a 500 ms delay
l
o
a
t
s
w
o
r
k
,
t
o
o
Sometimes you might need to delay for known, different increments of time. In that case you can iterate through a list of different delay periods with a for
loop:
有时您可能需要延迟已知的不同时间增量。 在这种情况下,您可以使用for
循环遍历不同延迟时间的列表:
import time
for i in [.5, 1, 2, 3, 4]:
time.sleep(i)
print(f"Delayed for {i} seconds")
Output:
输出:
Delayed for 0.5 seconds
Delayed for 1 seconds
Delayed for 2 seconds
Delayed for 3 seconds
Delayed for 4 seconds
As you can imagine, there's a lot that you can do with the sleep()
function. Now go ahead and try it in your own programs – no need to sleep on it!
您可以想象, sleep()
函数可以做很多事情。 现在继续尝试在您自己的程序中尝试–无需睡觉!
更多信息: (More Information:)
Time module documentation on the sleep function.
有关睡眠功能的时间模块文档 。
更多Python教程: (More Python tutorials:)
Python for Everybody from Dr. Chuck
翻译自: https://www.freecodecamp.org/news/time-delay-python-sleep-function/
c语言延迟函数sleep