gpt4 book ai didi

Haskell parMap 和并行性

转载 作者:行者123 更新时间:2023-12-04 04:35:36 28 4
gpt4 key购买 nike

我有一个康威生命游戏的实现。如果可能的话,我想通过使用并行性来加速它。

life :: [(Int, Int)] -> [(Int, Int)]
life cells = map snd . filter rules . freq $ concatMap neighbours cells
where rules (n, c) = n == 3 || (n == 2 && c `elem` cells)
freq = map (length &&& head) . group . sort

parLife :: [(Int, Int)] -> [(Int, Int)]
parLife cells = parMap rseq snd . filter rules . freq . concat $ parMap rseq neighbours cells
where rules (n, c) = n == 3 || (n == 2 && c `elem` cells)
freq = map (length &&& head) . group . sort

neigbours :: (Int, Int) -> [(Int, Int)]
neighbours (x, y) = [(x + dx, y + dy) | dx <- [-1..1], dy <- [-1..1], dx /= 0 || dy /= 0]

在分析中,邻居占了所花费时间的 6.3%,所以虽然很小,但我预计通过并行映射它会显着加快速度。

我用一个简单的功能进行了测试
main = print $ last $ take 200 $ iterate life fPent
where fPent = [(1, 2), (2, 2), (2, 1), (2, 3), (3, 3)]

并将并行版本编译为
ghc --make -O2 -threaded life.hs

并将其作为
./life +RTS -N3

事实证明,并行版本速度较慢。我在这里错误地使用了 parMap 吗?这甚至是可以使用并行性的情况吗?

最佳答案

我不认为你的测量是正确的。您的 parLife确实比life快一点.事实上,在我的机器(Phenom X4,4 核)上,前者只需要后者大约 92.5% 的时间,考虑到你说你期望只有 6% 的改进,这是相当不错的。

您的基准测试设置是什么?您是否尝试过使用 criterion ?这是我所做的:

import Criterion
import Criterion.Main

-- your code, minus main

runGame f n = last $ take n $ iterate f fPent
where fPent = [(1, 2), (2, 2), (2, 1), (2, 3), (3, 3)]

main = defaultMain
[ bench "No parallelism 200" $ whnf (runGame life) 200
, bench "Parallelism 200" $ whnf (runGame parLife) 200 ]

使用 ghc --make -O2 -o bench 编译并与 ./bench -o bencht.hmtl +RTS -N3 一起运行.

Here's the detailed result of the report .

关于Haskell parMap 和并行性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12224842/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com