首页
学习
活动
专区
圈层
工具
发布

python 多线程 性能评估(并行编程 10)

如果程序没做什么操作,多线程的性能比单线程差

运行结果:

starting tests non_threaded (1 iters) 0.000001 seconds threaded (1 threads) 0.000139 seconds Iterations complete non_threaded (2 iters) 0.000001 seconds threaded (2 threads) 0.000289 seconds Iterations complete non_threaded (4 iters) 0.000002 seconds threaded (4 threads) 0.000577 seconds Iterations complete non_threaded (8 iters) 0.000003 seconds threaded (8 threads) 0.001275 seconds Iterations complete ##################### from threading import Thread

def function_to_run(): pass

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 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 num_threads = [1, 2, 4, 8] print('starting tests') for i in num_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 threads)" % i, best_result) print('Iterations complete')


程序做大量计算的时候,多线程的性能和单线程差不多。做计算的,应该使用多进程

starting tests non_threaded (1 iters) 0.001805 seconds threaded (1 threads) 0.001993 seconds Iterations complete non_threaded (2 iters) 0.003609 seconds threaded (2 threads) 0.004139 seconds Iterations complete non_threaded (4 iters) 0.007224 seconds threaded (4 threads) 0.008225 seconds Iterations complete non_threaded (8 iters) 0.014513 seconds threaded (8 threads) 0.016649 seconds Iterations complete


在进行大量IO操作的时候,多线程的性能比单线程好

starting tests non_threaded (1 iters) 0.049067 seconds threaded (1 threads) 0.049898 seconds Iterations complete non_threaded (2 iters) 0.104077 seconds threaded (2 threads) 0.060791 seconds Iterations complete non_threaded (4 iters) 0.241385 seconds threaded (4 threads) 0.093600 seconds Iterations complete

下一篇
举报
领券