用time模块中的perf_counter函数是比较准确的,包含了sleep时间。
import socket
from time import perf_counter
import timeit
def blocking_way():
with socket.socket() as sock:
sock.connect(('baidu.com', 80))
request = 'GET / HTTP /1.0\r\nHost: baidu.com\r\n\r\n'
sock.send(request.encode('ascii'))
response = b''
chunk = sock.recv(4096)
while chunk:
response += chunk
chunk = sock.recv(4096)
return response
def sync_way():
res = []
for i in range(10):
res.append(blocking_way())
return len(res)
if __name__ == '__main__':
# perf_counter包含time.sleep()的时间(system-wide),process_time不包含
# time.sleep()的时间(process-wide),单位为s(perf_counter_ns单位为ns)
# 这两款计时器是比较精确的。
# 如果想要统计一小段代码(snippet)的用时,可以用timeit.timeit()函数,传入的
# 参数中stmt为待测试的代码(字符串或者函数名),setup为stmt代码运行前的准备代码,
# 运行完后才开始计时,timer为计时器,默认选择为perf_counter,number为stmt的
# 运行次数,默认为10000?
tic = perf_counter()
sync_way()
toc = perf_counter()
elapsed = toc - tic
# print('time elapsed: %.2f s' % elapsed)
print('time elapsed: %.2f s' % timeit.timeit(sync_way, number=10))