gpt4 book ai didi

python - 多线程使进程变慢

转载 作者:行者123 更新时间:2023-11-28 21:51:03 30 4
gpt4 key购买 nike

<分区>

我有以下任务,我想通过多线程 (python3) 加快速度。

import threading, time

q = []

def fill_list():
global q
while True:
q.append(1)
if len(q) >= 1000000000:
return

第一个 main 不使用多线程:

t1 = time.clock()
fill_list()
tend = time.clock() - t1
print(tend)

结果运行时间为 145 秒。

第二个调用两个线程:

t1 = time.clock()
thread1 = threading.Thread(target=fill_list, args=())
thread2 = threading.Thread(target=fill_list, args=())

thread1.start()
thread2.start()

thread1.join()
thread2.join()

tend = time.clock() - t1
print(tend)

这需要 152 秒才能完成。

最后,我添加了第三个线程。

t1 = time.clock()
thread1 = threading.Thread(target=fill_list, args=())
thread2 = threading.Thread(target=fill_list, args=())
thread3 = threading.Thread(target=fill_list, args=())

thread1.start()
thread2.start()
thread3.start()

thread1.join()
thread2.join()
thread3.join()

tend = time.clock() - t1
print(tend)

这需要 233 秒才能完成。

显然,我添加的线程越多,处理时间就越长,但我不确定为什么。这是对多线程的基本误解,还是我的代码中存在错误,只是多次重复任务而不是参与同一任务?

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com