简体   繁体   English

C#会内联这些功能吗?

[英]Will C# inline these functions?

I'm writing a performance-critical application in C# and the core operation is weight calculations. 我正在用C#编写一个性能关键型应用程序,核心操作是权重计算。 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);
}

All the calls are done from within the same class so all the variables are accessible. 所有调用都在同一个类中完成,因此所有变量都可以访问。 Can C# inline these function calls? C#可以内联这些函数调用吗? 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);
        }
    }
}

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. 如果这甚至可以提高10%的速度,那么它是完全值得的。 I can't easily benchmark by manually inlining them for comparison since I'd have to rewrite a lot of code. 我不能通过手动内联它们进行比较来轻松进行比较,因为我必须重写大量代码。

So my question is CAN C# inline these calls? 所以我的问题是CAN C#内联这些调用? And if so, how can I find out IF they have been inlined? 如果是这样,我怎么能知道他们是否被内联?

Inlining happens at JIT compilation, so you need to inspect code at runtime to observe inlining. 内联发生在JIT编译中,因此您需要在运行时检查代码以观察内联。 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. 这可以使用调试器来完成,但请记住,如果CLR检测到存在调试器,则会禁用各种优化,因此您需要在编译方法后附加调试器。

Please see these answers for some info on how you can find the method using WinDbg/SOS. 有关如何使用WinDbg / SOS查找方法的一些信息,请参阅这些 答案

您可以在此属性中使用MethodImplOptions.AggressiveInlining: http//msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimplattribute.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM