当前位置: 首页 > 面试题库 >

在Windows上的Python中演示多核加速的一些示例代码是什么?

须峰
2023-03-14
问题内容

我在Windows上使用Python 3并试图构建一个玩具示例,演示使用多个CPU内核如何加快计算速度。玩具示例是Mandelbrot分形的渲染。

至今:

  • 我避免了线程化,因为全局解释器锁定在这种情况下禁止多核
  • 我放弃了在Windows上无法使用的示例代码,因为它缺乏Linux的分叉功能
  • 尝试使用“多处理”包。我声明p = Pool(8)(8是我的内核数),并使用p.starmap(..)委派工作。这应该会产生多个“子进程”,这些窗口将自动将窗口委派给不同的CPU

但是,无论是由于开销还是没有实际的多重处理,我都无法证明任何加速。因此,具有明显加速性的玩具示例指针将非常有帮助:-)

编辑: 谢谢!这将我推向正确的方向,现在我得到了一个可行的示例,该示例演示了具有4个内核的CPU的速度提高了一倍。
我的代码的副本与“讲义”在这里:https :
//pastebin.com/c9HZ2vAV

我决定使用Pool(),但稍后将尝试@ 16num指出的“ Process”替代方法。下面是Pool()的代码示例:

    p = Pool(cpu_count())

    #Unlike map, starmap only allows 1 input. "partial" provides a workaround
    partial_calculatePixel = partial(calculatePixel, dataarray=data) 
    koord = []
    for j in range(height):
        for k in range(width):
            koord.append((j,k))

    #Runs the calls to calculatePixel in a pool. "hmm" collects the output
    hmm = p.starmap(partial_calculatePixel,koord)

问题答案:

演示多处理速度非常简单:

import multiprocessing
import sys
import time

# multi-platform precision clock
get_timer = time.clock if sys.platform == "win32" else time.time

def cube_function(num):
    time.sleep(0.01)  # let's simulate it takes ~10ms for the CPU core to cube the number
    return num**3

if __name__ == "__main__":  # multiprocessing guard
    # we'll test multiprocessing with pools from one to the number of CPU cores on the system
    # it won't show significant improvements after that and it will soon start going
    # downhill due to the underlying OS thread context switches
    for workers in range(1, multiprocessing.cpu_count() + 1):
        pool = multiprocessing.Pool(processes=workers)
        # lets 'warm up' our pool so it doesn't affect our measurements
        pool.map(cube_function, range(multiprocessing.cpu_count()))
        # now to the business, we'll have 10000 numbers to quart via our expensive function
        print("Cubing 10000 numbers over {} processes:".format(workers))
        timer = get_timer()  # time measuring starts now
        results = pool.map(cube_function, range(10000))  # map our range to the cube_function
        timer = get_timer() - timer  # get our delta time as soon as it finishes
        print("\tTotal: {:.2f} seconds".format(timer))
        print("\tAvg. per process: {:.2f} seconds".format(timer / workers))
        pool.close()  # lets clear out our pool for the next run
        time.sleep(1)  # waiting for a second to make sure everything is cleaned up

当然,在这里我们只是模拟10ms /数字的计算,您可以cube_function用任何CPU负担的方法代替实际演示。结果符合预期:

Cubing 10000 numbers over 1 processes:
        Total: 100.01 seconds
        Avg. per process: 100.01 seconds
Cubing 10000 numbers over 2 processes:
        Total: 50.02 seconds
        Avg. per process: 25.01 seconds
Cubing 10000 numbers over 3 processes:
        Total: 33.36 seconds
        Avg. per process: 11.12 seconds
Cubing 10000 numbers over 4 processes:
        Total: 25.00 seconds
        Avg. per process: 6.25 seconds
Cubing 10000 numbers over 5 processes:
        Total: 20.00 seconds
        Avg. per process: 4.00 seconds
Cubing 10000 numbers over 6 processes:
        Total: 16.68 seconds
        Avg. per process: 2.78 seconds
Cubing 10000 numbers over 7 processes:
        Total: 14.32 seconds
        Avg. per process: 2.05 seconds
Cubing 10000 numbers over 8 processes:
        Total: 12.52 seconds
        Avg. per process: 1.57 seconds

现在,为什么不100%线性?嗯,首先,它需要一些时间来图/数据分配给子流程,并把它找回来,有一些成本的上下文切换,还有一些用我的CPU不时其他任务,time.sleep()不是完全精确(也不可能在非RT
OS上使用)…但是结果大致上可用于并行处理。



 类似资料:
  • 本文向大家介绍Python 多核并行计算的示例代码,包括了Python 多核并行计算的示例代码的使用技巧和注意事项,需要的朋友参考一下 以前写点小程序其实根本不在乎并行,单核跑跑也没什么问题,而且我的电脑也只有双核四个超线程(下面就统称核好了),觉得去折腾并行没啥意义(除非在做IO密集型任务)。然后自从用上了32核128GB内存,看到 htop 里面一堆空载的核,很自然地就会想这个并行必须去折腾一

  • 本文向大家介绍python+matplotlib演示电偶极子实例代码,包括了python+matplotlib演示电偶极子实例代码的使用技巧和注意事项,需要的朋友参考一下 使用matplotlib.tri.CubicTriInterpolator.演示变化率计算: 完整实例: 总结 以上就是本文关于python+matplotlib演示电偶极子实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可

  • 本文向大家介绍Python方法的延迟加载的示例代码,包括了Python方法的延迟加载的示例代码的使用技巧和注意事项,需要的朋友参考一下 数据挖掘的过程中,数据进行处理是一重要的环节,我们往往会将其封装成一个方法,而有的时候这一个方法可能会被反复调用,每一次都对数据进行处理这将是一个很耗时耗资源的操纵,那么有没有办法将计算后的结果 缓存 起来达到 调用一次,处处运行 的效果,经过一番研究在 lazy

  • 学习目标: 通过一个简单完整的MVC实例,了解控制器文件(Controller)、模型文件(Model)、视图文件(View)的所在的目录路径。更好地理解DoitPHP框架的开发规则。 创建数据表: DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `user_id` mediumint(8) unsigned NOT NULL AUTO

  • 问题内容: 我有一个小的代码示例,我想在方法的Javadoc注释中包括它。 问题是代码示例显示在Javadoc中,没有换行符,很难阅读。 我猜我认为代码标签可以处理换行符是错误的。格式化Javadoc注释中的代码示例的最佳方法是什么? 问题答案: 除了已经提到的标签之外,您还应该使用JavaDoc注释,当涉及到HTML实体问题(尤其是泛型)时,这将使工作变得更加轻松,例如: 将给出正确的HTML输

  • 本文向大家介绍python验证码识别的示例代码,包括了python验证码识别的示例代码的使用技巧和注意事项,需要的朋友参考一下 写爬虫有一个绕不过去的问题就是验证码,现在验证码分类大概有4种: 图像类 滑动类 点击类 语音类 今天先来看看图像类,这类验证码大多是数字、字母的组合,国内也有使用汉字的。在这个基础上增加噪点、干扰线、变形、重叠、不同字体颜色等方法来增加识别难度。 相应的,验证码识别大体