简体   繁体   English

Noop方法避免c#编译器优化掉一个临时变量

[英]Noop method to avoid c# compiler optimize away a temp variable

in a derivative calculation context I need to make sure x and x+h differ by an exactly representable number, so I have done this: 在衍生计算上下文中,我需要确保x和x + h之间有一个完全可表示的数字,所以我这样做了:

var temp = x + deltaX;
DoNothing(temp);
deltaX = temp - x;

DoNothing() method being there in order to prevent temp to be optimized away. 存在DoNothing()方法以防止temp被优化掉。

Is that correct way of handling this? 这是正确的处理方式吗?

That compiler optimization you are worried about is invalid with .NET. 您担心的编译器优化对.NET无效。 It's known to be done in C++ with "fast math" compiler settings. 众所周知,它是在C ++中使用“快速数学”编译器设置完成的。 .NET guarantees IEEE floating point behavior with the exception that excess precision is allowed (not a problem here). .NET保证IEEE浮点行为,但允许过多的精度(这里不是问题)。 The optimization would be value-changing in general so it's forbidden. 优化通常会改变价值,因此被禁止。

If you want to clear compiler knowledge of a value I always use: 如果你想清除编译器的值,我总是使用:

[MethodImplOptions(NoInlining)]
T F<T>(T x) { return x; }

This is not guaranteed to work but it does with all JITs that are in existence at the moment. 这不能保证有效,但它确实适用于目前存在的所有JIT。 The .NET JITs are so weak at optimizing that I doubt they will add the kind of data flow analysis that would make this trick stop working. .NET JIT在优化方面非常薄弱,我怀疑它们会添加那种会使这个技巧停止运行的数据流分析。

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

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