【问题标题】:What is the simplest method to achieve 100% CPU usage in F#?在 F# 中实现 100% CPU 使用率的最简单方法是什么?
【发布时间】:2018-08-05 11:56:27
【问题描述】:

有时我编写的代码希望能够使 CPU 完全饱和。 例如,要计算 Mandelbrot 集,您可能会使用如下内容:

    type MandelbrotPoint =
        |Escaped of int
        |NotEscaped

    let getIterationCount maxIters (c:Complex) =
        let rec innerFunction iters (z:Complex) =
            match z.Magnitude, iters with
            |m, i when m > 2.0 -> Escaped i
            |_, i when i > maxIters -> NotEscaped
            |_ -> innerFunction (iters + 1) (z * z + c)
        innerFunction 0 c

    let getIterationCounts (topLeft:Complex) pixelWidth pixelHeight realWidth =
        let xGap = realWidth / ((pixelWidth - 1) |> float)

        [|for iY in 0 .. (pixelHeight - 1) do
                for iX in 0 .. (pixelWidth - 1) do
                    yield Complex(topLeft.Real + xGap * (float iX), topLeft.Imaginary - xGap * (float iY))
        |]
        |> Array.Parallel.map (getIterationCount 1000)

天真地,我希望这会以接近 100% 的速度运行直到完成,但它会在 25% 和 60% 之间反弹。

我知道,计算经常受到数据进出 CPU 缓存所需时间的限制,但这应该不是问题,对吧?要移动的数据很多,只是简单的迭代计算,不是吗?

【问题讨论】:

  • 你可能想看看这个:stackoverflow.com/questions/40370575/…>
  • 我尝试运行代码,如果分辨率低,我会得到与您描述的相似的结果,例如。 1280 x 1280,但如果我将分辨率提高到 12800 x 1280,那么我的 CPU 利用率将达到 99%。

标签: performance f# cpu-usage


【解决方案1】:

在我的 4 核 8 线程 CPU 上,以下简单的 sn-p 通过 FSI 进程确实接近 100% 的 CPU 饱和度:

let consume (x: int) =
    while true do
        let  _ = x*x
        ()

[|0..7|] |> Array.Parallel.iter consume

【讨论】:

  • 是的,我的也是。那么我们是否可以得出结论,我上面代码中的瓶颈毕竟与内存操作有关?
  • 我不是 CPU 细节方面的专家。然而,我的思路却从相反的方向转变。非常简单,忽略托管代码和操作系统的因素 - 如果我们在一些最简单的重复活动上短路所有 CPU,它可能会导致 CPU 饱和。看起来确实如此。
  • 问题可能是非并发垃圾回收造成的。
猜你喜欢
  • 1970-01-01
  • 2011-03-21
  • 2023-03-20
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 2013-08-07
相关资源
最近更新 更多