最近对python比较感兴趣,想对现有的项目移植到python上玩玩。
对于多线程,看个例子:
import time
import urllib2
def get_responses():
urls = ['http://www.amazon.com', 'http://www.ebay.com', 'http://www.alibaba.com', 'http://www.reddit.com']
start = time.time()
for url in urls:
print url
resp = urllib2.urlopen(url)
print resp.getcode()
print "Elapsed time: %s" % (time.time()-start)
get_responses()
输出:
http://www.amazon.com
200
http://www.ebay.com
200
http://www.alibaba.com
200
http://www.reddit.com
200
Elapsed time: 5.67659378052
[Finished in 5.9s]
多线程的版本:
import time
import urllib2
from threading import Thread
class GetUrlThread(Thread):
def __init__(self, url):
self.url = url
super(GetUrlThread, self).__init__()
def run(self):
resp = urllib2.urlopen(self.url)
print self.url, resp.getcode()
def get_responses():
urls = ['http://www.amazon.com', 'http://www.ebay.com', 'http://www.alibaba.com', 'http://www.reddit.com']
start = time.time()
threads = []
for url in urls:
t = GetUrlThread(url)
threads.append(t)
t.start()
for t in threads:
t.join()
print "Elapsed time: %s" % (time.time()-start)
get_responses()
开销:
http://www.alibaba.com 200
http://www.ebay.com 200
http://www.reddit.com 200
http://www.amazon.com 200
Elapsed time: 3.85897302628
[Finished in 4.2s]
果然减少了时间,四个线程同时跑,还是节省了时间。
代码完全参考 http://agiliq.com/blog/2013/09/understanding-threads-in-python/