且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-08-21 22:26:37

此对比说明了一件事:

如果是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')
        

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