python编写的用于测试网站访问速率的代码片段,可以输出打开某url的时间,访问100次的平均时间,最大时间和最小时间等等
来源:http://www.75271.com
def Process(url,n): minSpan = 10.0 maxSpan = 0.0 sumSpan= 0.0 over1s = 0 for i in range(n): startTime = datetime.datetime.now() try: res = urllib2.urlopen(url,timeout=10) except: pass endTime = datetime.datetime.now() span = (endTime-startTime).total_seconds() sumSpan = sumSpan + span if span < minSpan: minSpan = span if span > maxSpan: maxSpan = span #超过一秒的 if span>1: over1s=over1s + 1 print(u'%s Spent :%s seconds'%(url,span)) print(u'requested:%s times,Total Spent:%s seconds,avg:%s seconds, max:%s seconds,min:%s seconds,over 1 secnod:%s times'%(n,sumSpan,sumSpan/n,maxSpan,minSpan,over1s)) print('\n') if __name__=='__main__': Process('http://www.baidu.com',100)