以下代码的结果将因在后台启动还是没有启动调试器而不同。只有在开启优化时才会有差异。
这是结果:
-> 带优化: 1000 2008 3016 1001 2009 3007 ...
-> 不带优化(预期的结果) 1000 1008 1016 1001 1009 1017 ...
代码:
The behavior of the error depends on the number of iterations of the inner loop (everything works fine when x<5). Interestingly, the error does not occur when I use.
这是结果:
-> 带优化: 1000 2008 3016 1001 2009 3007 ...
-> 不带优化(预期的结果) 1000 1008 1016 1001 1009 1017 ...
代码:
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace OptimizerTest
{
public class Test
{
int dummy;
public void TestFunction(int stepWidth)
// stepWidth must be a parameter
{
for (int step = 0; step < stepWidth; step++)
{
dummy = step + 1000;
// addition with constant ( same value as later !)
for (int x = 0; x < 20; x += stepWidth)
{
int index = x + 1000 + step;
// constant must be same as above and ?!?!
// int index = x + step + 1000; works !!!!!
Console.Write("\n\r" + index);
}
}
}
[MethodImpl(MethodImplOptions.NoOptimization)]
public void TestFunctionNoOptimization(int stepWidth)
{
for (int step = 0; step < stepWidth; step++)
{
dummy = step + 1000;
for (int x = 0; x < 20; x += stepWidth)
{
int index = x + 1000 + step;
Console.Write("\n\r" + index);
}
}
}
}
class Program
{
/// <summary>
/// Result differs from Start with F5 to Ctrl-F5
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Test test = new Test();
Console.Write("\n\r---------\n\roptimized result\n\r-------------" );
test.TestFunction(8);
Console.Write("\n\r---------\n\rnot optimized result\n\r-------------");
test.TestFunctionNoOptimization(8);
Console.Write("\n\r---------\n\rpress any key");
Console.ReadKey();
}
}
}
错误的行为取决于内部循环的迭代次数(x<5时一切正常)。非常有趣的是,当我使用
时,错误不会发生。The behavior of the error depends on the number of iterations of the inner loop (everything works fine when x<5). Interestingly, the error does not occur when I use.
int index = x + step + 1000;
而不是
int index = x + 1000 + step;
我正在使用Visual Studio 2010 SP1,并尝试了.NET Framework从2.0到4.0.3。 我一直看到相同的结果。
是否有人知道这个错误或者能够重现它?