python中多线程与非线程的执行性能对比

本文通过对比测试展示了在不同类型的程序中使用多线程的效果。结果显示,在IO密集型应用中多线程能显著提高程序效率;而在CPU计算密集型任务中,多线程可能并无明显优势,甚至因为线程同步开销而降低效率。

此对比说明了一件事:

如果是IO型应用,多线程有优势,

如果是CPU计算型应用,多线程没必要,还有实现锁呢。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from threading import Thread

class threads_object(Thread):
    def run(self):
        function_to_run()

class nothreads_object(object):
    def run(self):
        function_to_run()

def non_threaded(num_iter):
    funcs = []
    for i in range(int(num_iter)):
        funcs.append(nothreads_object())
    for i in funcs:
        i.run()

def threaded(num_threads):
    funcs = []
    for i in range(int(num_threads)):
        funcs.append(threads_object())
    for i in funcs:
        i.start()
    for i in funcs:
        i.join()

def function_to_run():
    a, b = 0, 1
    for i in range(10000):
        a, b = b, a + b
    '''
    import requests
    for i in range(10):
        requests.get("http://10.25.174.41/")
    '''

def show_results(func_name, results):
    print("%-23s %4.6f seconds" % (func_name, results))


if __name__ == "__main__":
    import sys
    from timeit import Timer

    repeat = 100
    number = 1
    number_threads = [1, 2, 4, 8]

    print('Starting tests')
    for i in number_threads:
        t = Timer("non_threaded(%s)" \
                  % i, "from __main__ import non_threaded")
        best_result =\
                    min(t.repeat(repeat=repeat, number=number))
        show_results("non_threaded (%s iters) "\
                     %i, best_result)
        t = Timer("threaded(%s)" \
                  % i, "from __main__ import threaded")
        best_result =\
                    min(t.repeat(repeat=repeat, number=number))
        show_results("threaded (%s iters) "\
                     %i, best_result)

    print ('Iterations complete')
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值