最近在做一个性能测试,主要是http协议的,
开始想到用C的线程,在后来的试验中发现,C开发多线程还是比较麻烦的,
后来,想到了python,因为是http下载,curl的libcurl
def run(self):
real_uri=self.get_real_url()
if not real_uri:
return False
try:
try:
curl = pycurl.Curl()
curl.setopt(pycurl.URL, real_uri)
curl.setopt(pycurl.WRITEDATA, self.ofile)
curl.setopt(pycurl.NOPROGRESS, 0)
curl.setopt(pycurl.PROGRESSFUNCTION, self.progress)
#self.curl.setopt(pycurl.WRITEFUNCTION, counter)
curl.setopt(pycurl.FOLLOWLOCATION, 1)
curl.setopt(pycurl.MAXREDIRS, 5)
curl.setopt(pycurl.OPT_FILETIME, 1)
curl.setopt(pycurl.USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; InfoPath.2)")
#curl.setopt(pycurl.CONNECTTIMEOUT, 60)
#curl.setopt(pycurl.TIMEOUT, 300)
curl.setopt(pycurl.NOSIGNAL, 1)
curl.perform()
finally:
curl.close()
except Exception, e:
print "self.curl.perform() Exception : %s"%e
#if int(e[0]) == 28:
# print "This connection timeout [3000s], %s"%e
return True
实际测试,可以开到2000线程,内存仅仅使用了121M,2G的网卡跑满,感觉很强大
当然,由于这个测试只是取到平均下载速度,不需要实际下载到数据,故可以直接将下载到的数据>/dev/null 这样就可以避免I/O的瓶颈,
libcurl 刚好有一个回调函数,输出当前总下载的数据量
curl.setopt(pycurl.PROGRESSFUNCTION, self.progress)