gpt4 book ai didi

.net - 为什么 F# inline 会导致 11 倍的性能提升

转载 作者:行者123 更新时间:2023-12-03 12:35:10 25 4
gpt4 key购买 nike

我正在处理一些繁重的 cpu 绑定(bind)问题。当我使用 inline 时,我看到了很大的性能提升关键词。
我从标准 .net 库中创建了一个字典,传入了一个自定义键比较器,请参见下面的代码和计时结果

https://gist.github.com/4409734

在 Eq_cmp 上没有内联关键字

> perf_run 10000000 ;;
Real: 00:00:11.039, CPU: 00:00:11.029, GC gen0: 771, gen1: 3, gen2: 1
val it : unit = ()

在 Eq_cmp 上使用 inline 关键字
perf_run 10000000 ;;
Real: 00:00:01.319, CPU: 00:00:01.388, GC gen0: 1, gen1: 1, gen2: 1
val it : unit = ()
>

我还注意到 Gen 0 GC 的数量与内联代码和非内联代码的巨大差异。

有人可以解释为什么会有如此巨大的差异吗?

最佳答案

添加 inline 后,我可以在我的机器上以 3 倍的性能提升重现该行为关键词。
ILSpy 下并排反编译两个版本给出几乎相同的 C# 代码。显着的区别在于两个相等测试:

// Version without inline
bool IEqualityComparer<Program.Pair<a>>.System-Collections-Generic-IEqualityComparer(Program.Pair<a> x, Program.Pair<a> y)
{
a v@ = x.v@;
a v@2 = y.v@;
if (LanguagePrimitives.HashCompare.GenericEqualityIntrinsic<a>(v@, v@2))
{
a w@ = x.w@;
a w@2 = y.w@;
return LanguagePrimitives.HashCompare.GenericEqualityIntrinsic<a>(w@, w@2);
}
return false;
}

// Version with inline
bool IEqualityComparer<Program.Pair<int>>.System-Collections-Generic-IEqualityComparer(Program.Pair<int> x, Program.Pair<int> y)
{
int v@ = x.v@;
int v@2 = y.v@;
if (v@ == v@2)
{
int w@ = x.w@;
int w@2 = y.w@;
return w@ == w@2;
}
return false;
}
泛型相等的效率远低于专门的版本。

I also noticed the huge difference in the amount of Gen 0 GC with the inlined code and non inlined code.

Could someone explain why there is such a huge difference?


看看 GenericEqualityIntrinsic F# source code中的函数:

let rec GenericEqualityIntrinsic (x : 'T) (y : 'T) : bool = 
fsEqualityComparer.Equals((box x), (box y))
它对参数进行装箱,这解释了您的第一个示例中的大量垃圾。当 GC 过于频繁地发挥作用时,它会显着减慢计算速度。第二个示例(使用 inline )在 Pair 时几乎不会产生垃圾。是结构。
也就是说,这是 inline 的预期行为。在调用站点使用专用版本时的关键字。我的建议是始终尝试在相同的基准上优化和衡量您的代码。
您可能对一个非常相似的主题感兴趣 Why is this F# code so slow? .

关于.net - 为什么 F# inline 会导致 11 倍的性能提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14086580/

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