import time time.sleep(5) # Delays for 5 seconds. You can also use a float value.
这是另一个例子,约莫每分钟运转一次:
import timewhile True: print("This prints once a minute.") time.sleep(60) # Delay for 1 minute (60 seconds).
您能够sleep()在时候模块中运用该功用。它能够采纳浮动参数举行亚秒级分辨率。
from time import sleep sleep(0.1) # Time in seconds.
在 Python 里怎样手工举行耽误?
在一个线程中我发起就寝功用:
>>> from time import sleep >>> sleep(4)
这实际上停息了操作系统调用它的线程的处置惩罚,许可其他线程和历程在休眠时实行。
将其用于此目标,或仅仅是为了耽误实行某个功用。比方:
>>> def party_time(): ... print('hooray!') ... >>> sleep(3); party_time() hooray!
打了3秒后打印出来Enter。
运用sleep多个线程和历程的示例
再次,sleep停息你的线程 – 它运用零处置惩罚才能。
为了演示,建立一个如许的剧本(我首先在交互式Python 3.5 shell中尝试过这个,但子历程party_later由于某种原因找不到该函数):
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed from time import sleep, time def party_later(kind='', n=''): sleep(3) return kind + n + ' party time!: ' + __name__ def main(): with ProcessPoolExecutor() as proc_executor: with ThreadPoolExecutor() as thread_executor: start_time = time() proc_future1 = proc_executor.submit(party_later, kind='proc', n='1') proc_future2 = proc_executor.submit(party_later, kind='proc', n='2') thread_future1 = thread_executor.submit(party_later, kind='thread', n='1') thread_future2 = thread_executor.submit(party_later, kind='thread', n='2') for f in as_completed([ proc_future1, proc_future2, thread_future1, thread_future2,]): print(f.result()) end_time = time() print('total time to execute four 3-sec functions:', end_time - start_time) if __name__ == '__main__': main()
此剧本的示例输出:
thread1 party time!: __main__ thread2 party time!: __main__ proc1 party time!: __mp_main__ proc2 party time!: __mp_main__ total time to execute four 3-sec functions: 3.4519670009613037
以上就是在 Python 里怎样手工举行耽误的细致内容,更多请关注ki4网别的相干文章!