您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在 Python 里如何手工进行延迟

2024/4/7 22:36:23发布110次查看
我想知道如何在python脚本中加时间延迟。
import timetime.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 sleepsleep(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_completedfrom time import sleep, timedef 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 里如何手工进行延迟的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product