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
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