任务

def single():# 单进程单线程实现s = 0for i in range(1, N):s += math.sqrt(i)return s

结论

  • Python多线程无法利用多核
  • Python多进程可以利用多核
  • Numpy速度远超并行的Python代码
  • twisted无法利用多核

实现

import math
import multiprocessing
import threading
import timeitimport numpy as np
from twisted.internet import reactor
import timeN = 10000000def single():# 单进程单线程实现s = 0for i in range(1, N):s += math.sqrt(i)return sdef useThread():# 多线程实现total_sum = 0def go(beg, end):nonlocal total_sums = 0for i in range(beg, end):s += math.sqrt(i)total_sum += s  # python无法利用多核,所以这句话每个时刻只有一个线程在执行thread_count = 4per = math.ceil(N / thread_count)thread_list = []for i in range(thread_count):th = threading.Thread(target=go, args=(i * per, (i + 1) * per))thread_list.append(th)th.start()for th in thread_list:th.join()return total_sumdef useMultiprocess():# 使用多进程def go(q: multiprocessing.Queue, beg, end):s = 0for i in range(beg, end):s += math.sqrt(i)q.put(s)process_count = 4per = math.ceil(N / process_count)process_list = []q = multiprocessing.Queue()for i in range(process_count):th = multiprocessing.Process(target=go, args=(q, i * per, (i + 1) * per))process_list.append(th)th.start()for th in process_list:th.join()total_sum = 0try:while 1:x = q.get_nowait()total_sum += xexcept:passreturn total_sumdef useTwisted():# reactor是单例模式,一个进程只有一个reactor,一个reactor包括多个线程total_sum = 0ok_count = 0thread_count = 4def go(beg, end):nonlocal total_sums = 0for i in range(beg, end):s += math.sqrt(i)reactor.callFromThread(accumulate, s)def accumulate(s):nonlocal total_sumnonlocal ok_countok_count += 1if ok_count == thread_count:reactor.stop()total_sum += sdef process_work(q):reactor.suggestThreadPoolSize(thread_count)per = math.ceil(N / thread_count)for i in range(thread_count):reactor.callInThread(go, i * per, i * per + per)reactor.run()q.put(total_sum)q = multiprocessing.Queue()p = multiprocessing.Process(target=process_work, args=(q,))p.start()p.join()return q.get()def useTwisted2():# reactor是单例模式,一个进程只有一个reactor,一个reactor包括一个线程total_sum = 0thread_count = 4ok_count = 0beg_time = time.time()def go(beg, end):nonlocal total_sums = 0for i in range(beg, end):s += math.sqrt(i)reactor.callFromThread(accumulate, s)def accumulate(s):nonlocal total_sumnonlocal ok_counttotal_sum += sok_count += 1if ok_count == thread_count:print(time.time() - beg_time, "value", total_sum)reactor.suggestThreadPoolSize(thread_count)per = math.ceil(N / thread_count)for i in range(thread_count):reactor.callInThread(go, i * per, i * per + per)def useNumpy():a = np.linspace(1, N, N)return np.sum(np.sqrt(a))def main():for method in (single, useThread, useMultiprocess, useNumpy, useTwisted, useTwisted2):print(method.__name__, "result", method(), "time", timeit.timeit(method, number=10))reactor.run()if __name__ == '__main__':main()

twisted无法利用多核

from twisted.internet import threads, reactor
import time
import mathbeg_time = time.time()def go():print("go start")s = 0for i in range(10000000):s += math.sqrt(i + 1)print("go over", time.time() - beg_time)import timeitreactor.suggestThreadPoolSize(8)
print(timeit.timeit(go, number=1))
for i in range(10):reactor.callInThread(go)
reactor.run()

转载于:https://www.cnblogs.com/weiyinfu/p/10514432.html

Python并行实例相关推荐

  1. Python 并行分布式框架 Celery

    Celery 官网:http://www.celeryproject.org Celery 官方文档英文版:http://docs.celeryproject.org/en/latest/index. ...

  2. 用python实现视频换脸_超简单使用Python换脸实例

    换脸! 这段时间,deepfakes搞得火热,比方说把<射雕英雄传>里的朱茵换成了杨幂,看下面的图!毫无违和感! 其实早在之前,基于AI换脸的技术就得到了应用,比方说<速度与激情7& ...

  3. python简单编程例子-python简单实例训练(21~30)

    注意:我用的python2.7,大家如果用Python3.0以上的版本,请记得在print()函数哦!如果因为版本问题评论的,不做回复哦!! 21.题目:将一个正整数分解质因数.例如:输入90,打印出 ...

  4. python脚本实例手机端-python链接手机用Python实现命令行闹钟脚本实例

    前言: 这篇文章给大家介绍了怎样用python创建一个简单的报警,它可以运行在命令行终端,它需要分钟做为命令行参数,在这个分钟后会打印"wake-up"消息,并响铃报警,你可以用0 ...

  5. python爬虫实例-记录一次简单的Python爬虫实例

    本次的这篇文章主要是和大家分享了一篇关于记录一次简单的Python爬虫实例 ,有需要的小伙伴可以看一下. 主要流程分为: 爬取.整理.存储 1.其中用到几个包,包括 requests 用于向网站发送请 ...

  6. python经典案例-Python经典实例

    本书是Python经典实例解析,采用基于实例的方法编写,每个实例都会解决具体的问题和难题.主要内容有:数字.字符串和元组,语句与语法,函数定义,列表.集.字典,用户输入和输出等内置数据结构,类和对象, ...

  7. python程序格式框架的描述_python 程序语言设计(嵩天)-学习笔记(第二章python 程序实例解析)...

    第 2 章 python 程序实例解析 学习目标: 掌握解决计算问题的一般方法. 掌握python语言的基本语法,包括缩进.变量.命名等. 掌握python语言绘制图形的一般方法. 了解python标 ...

  8. 涵盖 14 大主题!最完整的 Python 学习实例集来了!

    机器学习.深度学习最简单的入门方式就是基于 Python 开始编程实战.最近闲逛 GitHub,发现了一个非常不错的 Python 学习实例集,完全是基于 Python 来实现包括 ML.DL 等领域 ...

  9. python组成不重复的三位数是多少_超星Python 练习实例1-组成多少个互不相同且无重复的三位数字...

    数字:1.2.3.4,能组成多少个互不相同且无重复数字的三位数?各是多少? 程序分析:可填在百位.十位.个位的数字都是1.2.3.4.组成所有的排列后再去 掉不满足条件的排列. 程序源代码: #!/u ...

最新文章

  1. 戴尔:发力互联互通 构建世界基础设施中心
  2. Linux 添加ssh 公钥访问
  3. PHP-FPM.CONF配置:日志文件、端口设置、动态静态选择设置
  4. Spring cloud整合zookeeper
  5. linux 内核同步--理解原子操作、自旋锁、信号量(可睡眠)、读写锁、RCU锁、PER_CPU变量、内存屏障
  6. 分区和分片的区别_Mysql分表和分区的区别、分库分表介绍与区别
  7. vue 项目文件介绍
  8. 【iOS开发】在一个Xcode页面建立多个工程
  9. 兰州交通大学计算机科学与技术专业排名,专业排行
  10. redmine-1.2.2安装服务(附图)
  11. java Hashtable 和 HashiMap 的区别
  12. MYSQL 8.0 OCP
  13. R语言:判断身份证号码真伪的函数编写
  14. Nmap的下载与基本命令运用
  15. 环信php修改头像,环信客服 如何正确设置用户的头像和昵称?
  16. 2019人工智能大数据精英大会圆满落幕(内附大会PPT干货资源)
  17. 驱动辅助资料(工具,目录,指令,debug经验)
  18. 阿里云 Aliplayer高级功能介绍(七):多分辨率
  19. 小破练习-嵌套循环及列表
  20. for...in 列表时,删除列表元素中的陷阱和解释

热门文章

  1. LinkedList源码
  2. [luogu3198] 玩具装箱
  3. QT5.10+MinGW+OpenCV3.4.2编译
  4. java线程day-01
  5. JAVA 语言如何进行异常处理,关键字: throws,throw,try,catch,finally分别代表什么意义? 在try块中可以抛 出异常吗?...
  6. Ubuntu12.04中eclipse提示框黑色背景色修改
  7. 从零开始带你部署springboot项目到ubuntu服务器05
  8. Linux操作Oracle(10)——plsql配置Oracle客户端方法【Oracle客户端安装、资源下载】详细教程
  9. 这可能是今年最值得推荐的数据分析工具!
  10. 计算机安全覆盖的内容有哪些,计算机网络的分类有哪些