【发布时间】:2012-04-26 14:58:12
【问题描述】:
现在我正在研究如何尽快从网站获取数据。为了获得更快的速度,我正在考虑使用多线程。这是我用来测试多线程和简单post的区别的代码。
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 自己的函数。
如果不考虑服务器阻止发布速度的可能限制,我还能做些什么来获得更快的速度?或者我可以修改的任何其他代码?非常感谢!
【问题讨论】:
-
线程在 python 中是一个坏主意,它很容易成为瓶颈并且可能被 GIL 困住,尝试多处理。
-
@JakobBowyer:线程是这里的实现细节,真正的重点是打开多个连接。 Python 中线程的 GIL 方面在这里没有任何作用。
-
@nightcracker,你真的应该在发表这样的声明之前阅读 GIL 和线程......从这里开始:PyCon 2010: Understanding the Python GIL
标签: python multithreading post tcp