timeit测试map【内置,线程,进程】

# 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迷心兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值