我有一个使用concurrent.futures模块在多线程下运行的Python 3.8脚本,可以在MacOS Catalina (Intel)上正常运行。但是当迁移到MacOS Monterey (Apple Silicon)后,由于使用单线程,Python代码运行时间较长。我使用的是Anaconda自带的x86_64 Python,并在Rosetta 2下运行。尝试了从Anaconda安装的Python 3.9,结果相同。如果有人能提供解决方案或变通方法,我将不胜感激。谢谢。
以下是一个测试代码以展示问题。在旧设备上,它运行了2轮并在10秒内完成。在新设备上,它运行了10轮并在50秒内完成。
import concurrent.futures
import time
pstart = time.time()
tasks = list(range(1,11))
def sleep_5s(task):
time.sleep(5)
print(f'Task {task} start at: {time.time()}')
def sleep_together(tasks):
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
for i,task in zip(tasks, executor.map(sleep_5s, tasks)):
pass
sleep_together(tasks)
print('Total run time', time.time()-pstart, 'seconds.')
更新:
我找到了根本原因。我没有插电源。在显示器休眠或屏幕保护程序启动5分钟后,Wi-Fi将断开连接。这是MacOS的新电源调整。以下是解决方案。