gpt4 book ai didi

haskell - randomInts 是否受到乒乓效应的影响?

转载 作者:行者123 更新时间:2023-12-03 05:02:23 31 4
gpt4 key购买 nike

下面的两段代码摘自RWH书籍的并发章节:

force :: [a] -> ()
force xs = go xs `pseq` ()
where go (_:xs) = go xs
go [] = 1

randomInts :: Int -> StdGen -> [Int]
randomInts k g = let result = take k (randoms g)
in force result `seq` result

randomInts是一个生成随机数列表的函数,用于测试并行排序算法的性能。书中已经提到,他们避免了上述代码中的一些潜在问题。书上是这么说的:

Invisible data dependencies.

When we generate the list of random numbers, simply printing the length of the list would not perform enough evaluation. This wouls evaluate the spine of the list, but not its elements. The actual random numbers would not be evaluated until the sort compares them.

This can have serious consequences for performance. The value of a random number depends on the value of the preceding random number in the list, but we have scattered the list elements randomly among our processor cores. If we did not evaluate the list elements prior to sorting, we would suffer a terrible “ping pong” effect: not only would evaluation bounce from one core to another, performance would suffer.

Try snipping out the application of force from the body of main above: you should find that the parallel code can easily end up three times slower than the non-parallel code.

所以基本上他们是说,通过使用 force 函数,他们避免了乒乓问题。但在解释force函数时,他们再次这样描述:

Notice that we don't care what's in the list; we walk down its spine to the end, then use pseq once. There is clearly no magic involved here: we are just using our usual understanding of Haskell's evaluation model. And because we will be using force on the left hand side of par or pseq, we don't need to return a meaningful value.

force函数的定义和上面的解释可以看出,各个列表元素中的元素不会被求值。那么 randomInts 函数实际上是如何避免乒乓效应的呢?这是书中的错误还是我理解有误?

最佳答案

randomInts 实际上似乎并没有受到乒乓 效应的影响。函数force实际上不仅是遍历列表的整个样条线,而且还对列表的元素进行求值。

import Control.Parallel (par, pseq)

force :: [a] -> ()
force xs = go xs `pseq` ()
where go (_:xs) = go xs
go [] = 1

在 ghci 中:

ghci > let a = [1..10]
ghci > :sprint a
a = _
ghci > force a
()
ghci > :sprint a
a = [1,2,3,4,5,6,7,8,9,10]

因此,force 函数会全面评估列表,使其免受乒乓效应的影响。

关于haskell - randomInts 是否受到乒乓效应的影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22749951/

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