仅使用单核的多处理

2024-05-19 13:08:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用模块perlin-noise创建一个FBM纹理,但它需要很长时间才能执行。我已经实现了multiprocessing,结果发现程序仍然运行在单个内核上。我试着寻找其他有同样问题的人,但大多数线程都有7年以上的历史,并且/或者涉及与不同操作系统相关的问题和解决方案

我的操作系统是Windows8.1,我有一个四核CPU,我运行的是Python 3.9.2

节目如下:

from perlin_noise import PerlinNoise
from multiprocessing import Pool

def world(n):
    noise1 = PerlinNoise(octaves=3, seed=1)
    noise2 = PerlinNoise(octaves=6, seed=1)
    noise3 = PerlinNoise(octaves=12, seed=1)
    noise4 = PerlinNoise(octaves=24, seed=1)
    noise5 = PerlinNoise(octaves=48, seed=1)
        
    world = []
    for i in range(n):
        row = []
        for j in range(n):
            noise_val =  noise1([i/n, j/n])
            noise_val += 0.5 * noise2([i/n, j/n])
            noise_val += 0.25 * noise3([i/n, j/n])
            noise_val += 0.125 * noise4([i/n, j/n])
            noise_val += 0.0625 * noise5([i/n, j/n])
            row.append(noise_val)
        world.append(row)
    
def main():
    start = time.time()
    nums = [128]
    p = Pool()
    p.map(world, nums)
    p.close()
    p.join()
    end = time.time()
    print(end - start)
    
if __name__ == '__main__':
    import time
    from distributed import Client
    client = Client()
    main()

那么,发生了什么事?我是否错误地认为多处理可以处理这些for循环

谢谢


Tags: fromimportforworldtimemainvalmultiprocessing
1条回答
网友
1楼 · 发布于 2024-05-19 13:08:22

它只使用一个过程的原因很简单。您在Pool.map中只传递了1个长度的列表

{}所做的是,提供的功能应用于提供的{}(在本例中,{})的每个元素,其中包含{}个工作进程

因为在nums中只有128个,所以它只创建一个任务,因此不会使用其他进程

正确的用法如下所示:

from multiprocessing import pool


def work(val):
    return hash(val ** 10000000)


if __name__ == '__main__':
    p = pool.Pool(8)

    with p:
        output = p.map(work, [i for i in range(1, 31)])

    print(output)

本例将有8个进程,因此使用8个逻辑核。由于我们给它提供了从1到30的数字,p.map将使用8个进程对这些数字中的每一个应用函数work,因此它最多可以同时运行8个函数

当我们运行它时,我们可以看到它的效果

enter image description here

当然,它使用了更多的进程来在进程之间进行通信,等等——我承认我不知道它的基本细节


旁注,为了使你的工作更有效率,你应该尽量避免附加太多内容

检查这个简单的示例,添加了大量的时间并测量了所花费的时间

>>> import timeit
>>> def appending():
...     output = []
...     for i in range(1000000):
...         output.append(i)
...     return output
... 
>>> def list_comp():
...     return [i for i in range(1000000)]

>>> print(f"{timeit.timeit(appending, number=100):.2}")
8.1

>>> print(f"{timeit.timeit(list_comp, number=100):.2}")
5.2

正如您所看到的,追加要比List comprehension慢得多-但这并不意味着不使用list.append-只是不要过度使用它

相关问题 更多 >