python中单线程、多线程和多进程的效率对比实验

对比实验

资料显示,如果多线程的进程是cpu密集型的,那多线程并不能有多少效率上的提升,相反还可能会因为线程的频繁切换,导致效率下降,推荐使用多进程;如果是io密集型,多线程进程可以利用io阻塞等待时的空闲时间执行其他线程,提升效率。所以我们根据实验对比不同场景的效率

| 操作系统 | cpu | 内存 | 硬盘 ||———–|——-|——|——–| | windows 10 | 双核 |8gb|机械硬盘|

(1)引入所需要的模块

import requests
import time
from threading import thread
from multiprocessing import process

(2)定义cpu密集的计算函数

def count(x, y):
# 使程序完成150万计算
c = 0
while c < 500000: c += 1 x += x y += y

(3)定义io密集的文件读写函数

def write():
f = open(“test.txt”, “w”)
for x in range(5000000):
f.write(“testwrite\n”)
f.close()
def read():
f = open(“test.txt”, “r”)
lines = f.readlines()
f.close()

(4) 定义网络请求函数

_head = {
‘user-agent’: ‘mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/48.0.2564.116 safari/537.36’}
url = “http://www.tieba.com”
def http_request():
try:
webpage = requests.get(url, headers=_head)
html = webpage.text
return {“context”: html}
except exception as e:
return {“error”: e}

(5)测试线性执行io密集操作、cpu密集操作所需时间、网络请求密集型操作所需时间

# cpu密集操作
t = time.time()
for x in range(10):
count(1, 1)
print(“line cpu”, time.time() – t)
# io密集操作
t = time.time()
for x in range(10):
write()
read()
print(“line io”, time.time() – t)
# 网络请求密集型操作
t = time.time()
for x in range(10):
http_request()
print(“line http request”, time.time() – t)

输出

cpu密集:95.6059999466、91.57099986076355 92.52800011634827、 99.96799993515015

io密集:24.25、21.76699995994568、21.769999980926514、22.060999870300293

网络请求密集型: 4.519999980926514、8.563999891281128、4.371000051498413、4.522000074386597、14.671000003814697

(6)测试多线程并发执行cpu密集操作所需时间

counts = []
t = time.time()
for x in range(10):
thread = thread(target=count, args=(1,1))
counts.append(thread)
thread.start()
e = counts.__len__()
while true:
for th in counts:
if not th.is_alive():
e -= 1
if e

Posted in 未分类

发表评论