Python并行实例
任务
def single():
    # 单进程单线程实现
    s = 0
    for i in range(1, N):
        s += math.sqrt(i)
    return s
结论
- Python多线程无法利用多核
- Python多进程可以利用多核
- Numpy速度远超并行的Python代码
- twisted无法利用多核
实现
import math
import multiprocessing
import threading
import timeit
import numpy as np
from twisted.internet import reactor
import time
N = 10000000
def single():
    # 单进程单线程实现
    s = 0
    for i in range(1, N):
        s += math.sqrt(i)
    return s
def useThread():
    # 多线程实现
    total_sum = 0
    def go(beg, end):
        nonlocal total_sum
        s = 0
        for i in range(beg, end):
            s += math.sqrt(i)
        total_sum += s  # python无法利用多核,所以这句话每个时刻只有一个线程在执行
    thread_count = 4
    per = 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_sum
def useMultiprocess():
    # 使用多进程
    def go(q: multiprocessing.Queue, beg, end):
        s = 0
        for i in range(beg, end):
            s += math.sqrt(i)
        q.put(s)
    process_count = 4
    per = 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 = 0
    try:
        while 1:
            x = q.get_nowait()
            total_sum += x
    except:
        pass
    return total_sum
def useTwisted():
    # reactor是单例模式,一个进程只有一个reactor,一个reactor包括多个线程
    total_sum = 0
    ok_count = 0
    thread_count = 4
    def go(beg, end):
        nonlocal total_sum
        s = 0
        for i in range(beg, end):
            s += math.sqrt(i)
        reactor.callFromThread(accumulate, s)
    def accumulate(s):
        nonlocal total_sum
        nonlocal ok_count
        ok_count += 1
        if ok_count == thread_count:
            reactor.stop()
        total_sum += s
    def 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 = 0
    thread_count = 4
    ok_count = 0
    beg_time = time.time()
    def go(beg, end):
        nonlocal total_sum
        s = 0
        for i in range(beg, end):
            s += math.sqrt(i)
        reactor.callFromThread(accumulate, s)
    def accumulate(s):
        nonlocal total_sum
        nonlocal ok_count
        total_sum += s
        ok_count += 1
        if 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 math
beg_time = time.time()
def go():
    print("go start")
    s = 0
    for i in range(10000000):
        s += math.sqrt(i + 1)
    print("go over", time.time() - beg_time)
import timeit
reactor.suggestThreadPoolSize(8)
print(timeit.timeit(go, number=1))
for i in range(10):
    reactor.callInThread(go)
reactor.run()
Python并行实例的更多相关文章
- python生成器并行实例
		生成器并行实例: send发送值被yield接受到赋值给baozi变量 #yield作用只是在这里保存这个值的当前状态然后返回之后在调用next,又回到yield #单纯调用next不会给yield传 ... 
- Python 并行分布式框架 Celery
		Celery 简介 除了redis,还可以使用另外一个神器---Celery.Celery是一个异步任务的调度工具. Celery 是 Distributed Task Queue,分布式任务队列,分 ... 
- 【转】Python 并行分布式框架 Celery
		原文链接:https://blog.csdn.net/freeking101/article/details/74707619 Celery 官网:http://www.celeryproject.o ... 
- python基础——实例属性和类属性
		python基础——实例属性和类属性 由于Python是动态语言,根据类创建的实例可以任意绑定属性. 给实例绑定属性的方法是通过实例变量,或者通过self变量: class Student(objec ... 
- python 发送邮件实例
		留言板回复作者邮件提醒 -----------2016-5-11 15:03:58-- source:python发送邮件实例 
- python Cmd实例之网络爬虫应用
		python Cmd实例之网络爬虫应用 标签(空格分隔): python Cmd 爬虫 废话少说,直接上代码 # encoding=utf-8 import os import multiproces ... 
- Python爬虫实例:爬取B站《工作细胞》短评——异步加载信息的爬取
		很多网页的信息都是通过异步加载的,本文就举例讨论下此类网页的抓取. <工作细胞>最近比较火,bilibili 上目前的短评已经有17000多条. 先看分析下页面 右边 li 标签中的就是短 ... 
- Python爬虫实例:爬取猫眼电影——破解字体反爬
		字体反爬 字体反爬也就是自定义字体反爬,通过调用自定义的字体文件来渲染网页中的文字,而网页中的文字不再是文字,而是相应的字体编码,通过复制或者简单的采集是无法采集到编码后的文字内容的. 现在貌似不少网 ... 
- Python爬虫实例:爬取豆瓣Top250
		入门第一个爬虫一般都是爬这个,实在是太简单.用了 requests 和 bs4 库. 1.检查网页元素,提取所需要的信息并保存.这个用 bs4 就可以,前面的文章中已经有详细的用法阐述. 2.找到下一 ... 
随机推荐
- 003.Keepalived搭建LVS高可用集群
			一 基础环境 1.1 IP规划 OS:CentOS 6.8 64位 节点类型 IP规划 主机名 类型 主 Director Server eth0:172.24.8.10 DR1 公共IP eth1: ... 
- 记录Ubuntu & Windows下安装PyV8
			https://blog.csdn.net/hanshileiai/article/details/51628173 
- XamarinSQLite教程添加测试数据
			XamarinSQLite教程添加测试数据 此时创建的Students表中是没有任何数据,也就是一个空表.为了方便测试App,开发者需要为表添加一些数据.操作步骤如下. (1)右击创建的Student ... 
- Django之模板2
			模板2 一 . 母版 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ... 
- 错误类型“Microsoft.Office.Interop.Word.ApplicationClass”未定义构造函数
			原文网址:http://zhidao.baidu.com/link?url=WcvaYFI1JeEGvbjD77nDbGp21sjaNCnCTRLGrU5YjwUGbHbhHJxQolKbsMZbZs ... 
- BZOJ2821 作诗(Poetize) 分块
			题意 算法 经验总结 代码 题意 不带修改,查询数列[1,n]中[l,r]内的出现正偶数次的数的个数, 数列中的数 <= 1e5, n <= 1e5, 强制在线 算法  查询的内容: 区 ... 
- 关于腾讯云服务器不能用公网ip访问的解决方案
			最近在腾讯云服务器上部署Javaweb项目,开始外网ip是可以访问到云服务器上的项目的,我重启了一下Tomcat之后发现端口号8080无法使用,此时的公网ip还是可以使用的,然后我重启了一下云服务器之 ... 
- Android:ViewGroup和View的Touch事件
			Android中ViewGroup和View中的Touch事件传递机制分析 关键字:GroupView:View:Touch事件 基础知识: onInterceptTouchEvent():在View ... 
- Apache自带压力测试工具----linux环境中ab命令简介及结果分析
			ab(apache bench)是apache下的一个工具,主要用于对web站点做压力测试, 基础用法: 其中-c选项为一次发送的请求数量,及并发量.-n选项为请求次数. 实验测试: [dev@web ... 
- 潭州课堂25班:Ph201805201 django 项目 第二课 git 版本控制  (课堂笔记)
			安装 git sudo apt-get install git 查看版本信息: git --version 演示: 创建个项目 创建文件夹 如果要对这个文件夹进行版本控制 先进到这个文件夹中, 命令查 ... 
