脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - python中的多cpu并行编程

python中的多cpu并行编程

2023-02-06 10:49toforu Python

这篇文章主要介绍了python中的多cpu并行编程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

多cpu并行编程

  • python多线程只能算并发,因为它智能使用一个cpu内核
  • python下pp包支持多cpu并行计算

安装

?
1
pip install pp

使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#-*- coding: UTF-8 -*-
import math, sys, time
import pp
def IsPrime(n):
    """返回n是否是素数"""
    if not isinstance(n, int):
        raise TypeError("argument passed to is_prime is not of 'int' type")
    if n < 2:
        return False
    if n == 2:
        return True
    max = int(math.ceil(math.sqrt(n)))
    i = 2
    while i <= max:
        if n % i == 0:
            return False
        i += 1
    return True
def SumPrimes(n):
    for i in xrange(15):
        sum([x for x in xrange(2,n) if IsPrime(x)])
    """计算从2-n之间的所有素数之和"""
    return sum([x for x in xrange(2,n) if IsPrime(x)])
inputs = (100000, 100100, 100200, 100300, 100400, 100500, 100600, 100700)
# start_time = time.time()
# for input in inputs:
#     print SumPrimes(input)
# print '单线程执行,总耗时', time.time() - start_time, 's'
# # tuple of all parallel python servers to connect with
ppservers = ()
#ppservers = ("10.0.0.1",)
if len(sys.argv) > 1:
    ncpus = int(sys.argv[1])
    # Creates jobserver with ncpus workers
    job_server = pp.Server(ncpus, ppservers=ppservers)
else:
    # Creates jobserver with automatically detected number of workers
    job_server = pp.Server(ppservers=ppservers)
print "pp 可以用的工作核心线程数", job_server.get_ncpus(), "workers"
start_time = time.time()
jobs = [(input, job_server.submit(SumPrimes,(input,), (IsPrime,), ("math",))) for input in inputs]#submit提交任务
for input, job in jobs:
    print "Sum of primes below", input, "is", job()# job()获取方法执行结果
print "多线程下执行耗时: ", time.time() - start_time, "s"
job_server.print_stats()#输出执行信息

执行结果

pp 可以用的工作核心线程数 4 workers
Sum of primes below 100000 is 454396537
Sum of primes below 100100 is 454996777
Sum of primes below 100200 is 455898156
Sum of primes below 100300 is 456700218
Sum of primes below 100400 is 457603451
Sum of primes below 100500 is 458407033
Sum of primes below 100600 is 459412387
Sum of primes below 100700 is 460217613
多线程下执行耗时:  15.4971420765 s
Job execution statistics:
 job count | % of all jobs | job time sum | time per job | job server
         8 |        100.00 |      60.9828 |     7.622844 | local
Time elapsed since server creation 15.4972219467
0 active tasks, 4 cores

submit 函数定义

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def submit(self, func, args=(), depfuncs=(), modules=(),
        callback=None, callbackargs=(), group='default', globals=None):
    """Submits function to the execution queue
 
        func - function to be executed  执行的方法
        args - tuple with arguments of the 'func' 方法传入的参数,使用元组
        depfuncs - tuple with functions which might be called from 'func' 传入自己写的方法 ,元组
        modules - tuple with module names to import  传入 模块
        callback - callback function which will be called with argument
                list equal to callbackargs+(result,)
                as soon as calculation is done
        callbackargs - additional arguments for callback function
        group - job group, is used when wait(group) is called to wait for
        jobs in a given group to finish
        globals - dictionary from which all modules, functions and classes
        will be imported, for instance: globals=globals()
    """

多核cpu并行计算

  • 多进程实现并行计算的简单示例
  • 这里我们开两个进程,计算任务也简洁明了
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 多进程
import multiprocessing as mp
def job(q, a, b):
    print('aaa')
    q.put(a**1000+b*1000# 把计算结果放到队列
# 多进程
if __name__ == '__main__':
    q = mp.Queue()  # 一个队列
    p1 = mp.Process(target=job, args=(q, 100, 200))
    p2 = mp.Process(target=job, args=(q, 100, 200))
    p1.start()
    p1.join()
    # print(p1.ident)
    p2.start()
    p2.join()
    res = q.get() + q.get()  # 读取队列,这里面保存了两次计算得到的结果
    print('result:', res)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://liuhuiyao.blog.csdn.net/article/details/72853750

延伸 · 阅读

精彩推荐
  • Pythonpython编程学习使用管道Pipe编写优化代码

    python编程学习使用管道Pipe编写优化代码

    大家好,今天这篇文章我将详细讲解 Pipe 如何让你的代码更加简洁的方法,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步...

    Python学习与数据挖掘10792022-03-04
  • Pythonpython OpenCV学习笔记直方图反向投影的实现

    python OpenCV学习笔记直方图反向投影的实现

    这篇文章主要介绍了python OpenCV学习笔记直方图反向投影的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    JS_XH5012021-01-13
  • Pythonpython 工具类之Queue组件详解用法

    python 工具类之Queue组件详解用法

    队列(queue)是一种先进先出的(First In First Out)的线性表,简称FIFO。队列允许在一端进行插入操作,而在另一端进行删除操作。允许插入的一端为队尾,...

    剑客阿良_ALiang6392022-02-19
  • PythonLinux下Python安装完成后使用pip命令的详细教程

    Linux下Python安装完成后使用pip命令的详细教程

    这篇文章主要介绍了Linux下Python安装完成后使用pip命令的详细教程,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下...

    子钦加油8212021-04-22
  • PythonPygame Event事件模块的详细示例

    Pygame Event事件模块的详细示例

    事件是Pygame的重要模块之一,比如鼠标点击、键盘敲击、游戏窗口移动、调整窗口大小、触发特定的情节、退出游戏等等,本文就详细的介绍一下具体用法...

    zx3472022-03-02
  • Python详解Python下Flask-ApScheduler快速指南

    详解Python下Flask-ApScheduler快速指南

    Flask是Python社区非常流行的一个Web开发框架,本文将尝试将介绍APScheduler应用于Flask之中,非常具有实用价值,需要的朋友可以参考下...

    bladestone9462021-04-15
  • PythonPython实现FTP文件定时自动下载的步骤

    Python实现FTP文件定时自动下载的步骤

    这篇文章主要介绍了Python实现FTP文件定时自动下载的示例,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下...

    Peanut_C12442021-08-16
  • PythonPython实现byte转integer

    Python实现byte转integer

    这篇文章主要介绍了Python实现byte转integer操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    Silbera10422021-11-22