gpt4 book ai didi

F#:为什么使用外部函数版本比将函数作为参数传递更快

转载 作者:行者123 更新时间:2023-12-04 21:37:23 25 4
gpt4 key购买 nike

使用直接外部函数的版本 (calc1) 大约需要 1 秒。

但是带有传递函数作为函数参数的版本(calc2)需要大约 2 秒,即慢 2 倍。为什么?

open System.Diagnostics
open System.Numerics

let width = 1920
let height = 1200
let xMin = -2.0
let xMax = 1.0
let yMin = -1.0
let yMax = 1.0
let scaleX x = float x * (xMax - xMin) / float width + xMin
let scaleY y = float y * (yMax - yMin) / float height - yMax

let fn (z:Complex) (c:Complex) = z * z + c

let calc1 width height =
let iterFn z c =
let rec iterFn' (z:Complex) c n =
if z.Magnitude > 2.0 || n >= 255 then n
else iterFn' (fn z c) c (n + 1)
iterFn' z c 0

Array.Parallel.init (width * height) (fun i ->
let x, y = i % width, i / width
let z, c = Complex.Zero, Complex(scaleX x, scaleY y)
(x, y, iterFn z c)
)

let calc2 width height fn =
let iterFn z c =
let rec iterFn' (z:Complex) c n =
if z.Magnitude > 2.0 || n >= 255 then n
else iterFn' (fn z c) c (n + 1)
iterFn' z c 0

Array.Parallel.init (width * height) (fun i ->
let x, y = i % width, i / width
let z, c = Complex.Zero, Complex(scaleX x, scaleY y)
(x, y, iterFn z c)
)

在F#交互中执行得到如下结果:
> calc1 width height |> ignore
Real: 00:00:00.943, CPU: 00:00:03.046, GC gen0: 10, gen1: 8, gen2: 2
val it : unit = ()

> calc2 width height fn |> ignore
Real: 00:00:02.033, CPU: 00:00:07.484, GC gen0: 9, gen1: 8, gen2: 1
val it : unit = ()

F# 4.0.1、.NET 4.6.1

最佳答案

我怀疑在第一种情况下,fn是内联的。

将其作为参数传递可防止发生此优化,因此速度较慢

关于F#:为什么使用外部函数版本比将函数作为参数传递更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34702922/

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