C#会内联这些功能吗? [英] Will C# inline these functions?

查看:73
本文介绍了C#会内联这些功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#编写性能至关重要的应用程序,其核心操作是权重计算.该函数如下所示:

I'm writing a performance-critical application in C# and the core operation is weight calculations. The function looks like this:

public void ForEachWeight(Action<int, int, float> action)
{
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            action(lower, upper, Weights[(lower * UpperLayerSize) + upper]);
        }
    }
}

它在几十个地方被调用,具有各种简单的功能,例如:

And it gets called in dozens of places with various simple functions like:

if (activationMethod == ActivationMethod.Binary) {
    ForEachWeight((lower, upper, weight) => upperLayer.Values[upper] += weight;
} else {
    ForEachWeight((lower, upper, weight) => upperLayer.Values[upper] += lowerLayer.Values[lower] * weight);
}

所有调用均在同一类中完成,因此可以访问所有变量. C#可以内联这些函数调用吗?我在想例如上述调用可以内联到这样的东西:

All the calls are done from within the same class so all the variables are accessible. Can C# inline these function calls? I'm thinking for example the above calls can be inlined to something like this:

if (activationMethod == ActivationMethod.Binary) {
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            upperLayer.Values[upper] += weight;
        }
    }
} else {
    for (int lower = 0; lower < LowerLayerSize; lower++) {
        for (int upper = 0; upper < UpperLayerSize; upper++) {
            upperLayer.Values[upper] += lowerLayer.Values[lower] * weight);
        }
    }
}

如果不是,则意味着成千上万的额外函数调用,我认为这是巨大的开销.如果这能提供10%的速度提升,那是完全值得的.由于必须重写很多代码,因此无法通过手动内联它们进行比较来轻松进行基准测试.

If it doesn't it means tens of thousands of extra function calls which I think are a huge overhead. If this gives even a 10% speed boost it's totally worth it. I can't easily benchmark by manually inlining them for comparison since I'd have to rewrite a lot of code.

所以我的问题是C#可以内联这些调用吗?如果是这样,我如何找出它们是否已内联?

So my question is CAN C# inline these calls? And if so, how can I find out IF they have been inlined?

推荐答案

内联在JIT编译时发生,因此您需要在运行时检查代码以观察内联.可以使用调试器完成此操作,但请记住,如果CLR检测到调试器的存在,则会禁用各种优化,因此,在编译方法之后,需要附加调试器.

Inlining happens at JIT compilation, so you need to inspect code at runtime to observe inlining. This can be done using the debugger, but keep in mind that if the CLR detects the presence of a debugger various optimizations are disabled, so you need to attach the debugger after the method has been compiled.

请参见这些 答案以获取有关如何使用WinDbg/SOS查找该方法的信息.

Please see these answers for some info on how you can find the method using WinDbg/SOS.

这篇关于C#会内联这些功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆