gpt4 book ai didi

python - 如何在python中使用多线程时获得更快的速度

转载 作者:太空狗 更新时间:2023-10-29 20:39:02 25 4
gpt4 key购买 nike

现在我正在研究如何以最快的速度从网站上获取数据。为了获得更快的速度,我正在考虑使用多线程。这是我用来测试多线程和简单帖子之间区别的代码。

import threading
import time
import urllib
import urllib2


class Post:

def __init__(self, website, data, mode):
self.website = website
self.data = data

#mode is either "Simple"(Simple POST) or "Multiple"(Multi-thread POST)
self.mode = mode

def post(self):

#post data
req = urllib2.Request(self.website)
open_url = urllib2.urlopen(req, self.data)

if self.mode == "Multiple":
time.sleep(0.001)

#read HTMLData
HTMLData = open_url.read()



print "OK"

if __name__ == "__main__":

current_post = Post("http://forum.xda-developers.com/login.php", "vb_login_username=test&vb_login_password&securitytoken=guest&do=login", \
"Simple")

#save the time before post data
origin_time = time.time()

if(current_post.mode == "Multiple"):

#multithreading POST

for i in range(0, 10):
thread = threading.Thread(target = current_post.post)
thread.start()
thread.join()

#calculate the time interval
time_interval = time.time() - origin_time

print time_interval

if(current_post.mode == "Simple"):

#simple POST

for i in range(0, 10):
current_post.post()

#calculate the time interval
time_interval = time.time() - origin_time

print time_interval

如您所见,这是一个非常简单的代码。首先我将模式设置为“简单”,我可以得到时间间隔:50s(可能我的速度有点慢:()。然后我将模式设置为“多重”,然后我得到时间间隔:35。由此可见,多线程其实是可以提速的,但是结果并没有想象中的那么好。我想获得更快的速度。

通过调试,我发现程序主要阻塞在open_url = urllib2.urlopen(req, self.data)这行代码,这行代码需要大量的时间来发送和接收来自指定网站的数据。我想也许我可以通过添加 time.sleep() 并在 urlopen 函数中使用多线程来获得更快的速度,但我不能这样做,因为它是 python 自己的功能。

如果不考虑服务器可能限制发帖速度,我还能做些什么来获得更快的速度?或者我可以修改的任何其他代码?非常感谢!

最佳答案

您做错的最大事情是您调用 thread.start()thread.join() 的方式,这对您的吞吐量影响最大:

for i in range(0, 10):
thread = threading.Thread(target = current_post.post)
thread.start()
thread.join()

每次循环,您都会创建一个线程,启动它,然后等待它完成在继续下一个线程之前。你根本没有同时做任何事情!

您可能应该做的是:

threads = []

# start all of the threads
for i in range(0, 10):
thread = threading.Thread(target = current_post.post)
thread.start()
threads.append(thread)

# now wait for them all to finish
for thread in threads:
thread.join()

关于python - 如何在python中使用多线程时获得更快的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10154487/

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