# coding=utf-8
from math import sqrt
from timeit import timeit
from concurrent.futures.process import ProcessPoolExecutor
from concurrent.futures.thread import ThreadPoolExecutor
def increase_price_by_10_percent(price):
# 第一:---------------------------------------
# price += price / 10 * 100
# return price
# 第二:---------------------------------------
price += price / 10 * 100
new_prices = []
for i in range(0, 200000):
new_prices.append(price + pow(price, 2))
new_prices = map(sqrt, new_prices)
new_prices = map(sqrt, new_prices)
return max(price, min(new_prices))
def increase_price_serial(price_list, increase_function):
results = list(map(increase_function, price_list))
return results
def increase_price_with_threads(price_list, increase_function):
pool = ThreadPoolExecutor(max_workers = 2)
results = list(pool.map(increase_function, price_list))
return results
def increase_price_with_subprocess(price_list, increase_function):
"""
测试进程的CPU性能
进程操作小数据和大数据的比较,
结论就是:进程适合大数据下的CPU密集型工作
"""
pool = ProcessPoolExecutor(max_workers = 2)
results = list(pool.map(increase_function, price_list))
return results
if __name__ == '__main__':
# 进程测试
stmt = "increase_price_with_subprocess([1, 2, 3, 4, 5, 6, 7, 8, 9, ], increase_price_by_10_percent)"
setup = "from __main__ import increase_price_with_subprocess,increase_price_by_10_percent"
result_date = timeit(stmt, setup, number = 100)
print(result_date) # 第一:11.543722665999999 第二:83.909480534
# 线程测试
stmt = "increase_price_with_threads([1, 2, 3, 4, 5, 6, 7, 8, 9, ], increase_price_by_10_percent)"
setup = "from __main__ import increase_price_with_threads,increase_price_by_10_percent"
result_date = timeit(stmt, setup, number = 100)
print(result_date) # 第一:0.05429845299999947 第二:156.08904959999998
# 一般测试
stmt = "increase_price_serial([1, 2, 3, 4, 5, 6, 7, 8, 9, ], increase_price_by_10_percent)"
setup = "from __main__ import increase_price_serial,increase_price_by_10_percent"
result_date = timeit(stmt, setup, number = 100)
print(result_date) # 第一:0.0002286930000003906 第二:168.92218752
timeit测试map【内置,线程,进程】
最新推荐文章于 2022-03-14 20:00:00 发布