请帮助理解Haskell Parallel

时间:2019-04-13 06:48:13

标签: haskell parallel-processing

我已经阅读了一些文档,以fibonacci为例。然后,我开始尝试使我的代码主要与list并行化。我的代码没有更快。

示例代码:

parMap :: (a -> b) -> [a] -> [b]
parMap f = withStrategy (parList rseq) . map f

parZipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
parZipWith f as = withStrategy (parList rseq) . zipWith f as

main = do
  let rips = parMap parseIPRange [] -- huge list of items like "192.168.3.1/24"
      result = parZipWith checkSubnets rips (tail rips ++ [IPRange 0 0])
  print result

我想我一定对整个事情都误会了。

PS:整个过程是https://github.com/magicloud/ip_helper的迁移,这是Rust与Rayon的迁移。

1 个答案:

答案 0 :(得分:4)

按照@ATayler的建议,我做了以下更改。

  1. 启用DeriveGeneric
  2. 导入GHC.Generics
  3. 派生我所有类型的Generic
  4. 使我需要的功能:
parMap :: (NFData b) => (a -> b) -> [a] -> [b]
parMap f = withStrategy (parList rdeepseq). map f
parFilter :: (NFData a) => (a -> Bool) -> [a] -> [a]
parFilter f = withStrategy (parList rdeepseq) . filter f
parZipWith :: (NFData c) => (a -> b -> c) -> [a] -> [b] -> [c]
parZipWith f as = withStrategy (parList rdeepseq). zipWith f as
parSortBy :: (NFData a) => (a -> a -> Ordering) -> [a] -> [a]
parSortBy f = withStrategy (parList rdeepseq) . sortBy f
  1. 在适当的时候给他们打电话。

现在,使用完整的CPU,时间可以减少到原始单线程线程的1/3。不确定是否可以进行其他主要优化。