gpt4 book ai didi

optimization - F#:部分应用和预计算

转载 作者:行者123 更新时间:2023-12-03 05:11:42 24 4
gpt4 key购买 nike

今天查看代码中的一个函数,我想知道是否可以将部分组合和优化结合起来:

let foo (X:float) y1 y2 dx = 
y1 + (y2 - y1) * dx / X

基本上,只需应用一个比率 - 因此前三个参数在给定循环内通常是相同的。

我想也许如果我这样做:

let foo2 (X:float) y1 y2 dx = 
let dy = (y2 - y1) / X
y1 + dy * dx

当我部分应用前三个参数时,F# 会变得聪明并为我进行优化,但在 Debug模式下,情况似乎并非如此(尽管我不确定我是否在正确的位置对其进行了测试)方式)。

问题是,这应该有效吗?如果没有,是否有更好的方法(除了编写另一个带有两个参数的函数之外)?

最佳答案

我认为大多数此类“神奇优化”都需要“效果分析”,而这只能由神话般的“足够智能的编译器”完成。

思考一下:

let Expensive x y = 
printfn "I am a side-effect of Expensive"
x + y // imagine something expensive

let F x y z =
let tmp = Expensive x y
z + tmp

printfn "Least chance of magic compiler optimization"
for i in 1..3 do
F 3 4 i

printfn "Slightly better chance"
let Part = F 3 4
for i in 1..3 do
Part i

printfn "Now for real"
let F2 x y =
let tmp = Expensive x y
(fun z -> z + tmp)

printfn "Of course this still re-does it"
for i in 1..3 do
F2 3 4 i

printfn "Of course this finally saves re-do-ing Expensive"
let Opt = F2 3 4
for i in 1..3 do
Opt i

(* output

Least chance of magic compiler optimization
I am a side-effect of Expensive
I am a side-effect of Expensive
I am a side-effect of Expensive
Slightly better chance
I am a side-effect of Expensive
I am a side-effect of Expensive
I am a side-effect of Expensive
Now for real
Of course this still re-does it
I am a side-effect of Expensive
I am a side-effect of Expensive
I am a side-effect of Expensive
Of course this finally saves re-do-ing Expensive
I am a side-effect of Expensive

*)

重点是,有关效果的语言语义要求编译器的行为与此完全相同,除非“昂贵”没有效果,并且编译器非常非常聪明,可以自行发现这一点。

关于optimization - F#:部分应用和预计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1431450/

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