前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 多线程 性能评估(并行编程 10)

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

作者头像
用户5760343
发布2019-07-30 11:07:12
5490
发布2019-07-30 11:07:12
举报
文章被收录于专栏:sktjsktj

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

运行结果:

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.07.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 如果程序没做什么操作,多线程的性能比单线程差
    • 运行结果:
      • 程序做大量计算的时候,多线程的性能和单线程差不多。做计算的,应该使用多进程
      • 在进行大量IO操作的时候,多线程的性能比单线程好
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档