2015-05-04 26 views
6

我在C#项目中遇到了一些令人困惑的Stopwatch结果。考虑下面的代码:秒表根据代码所在的位置给出不同的结果

static void Main(string[] args) 
{ 
    byte[] myEventArray = GetEventByteArrayFromDatabase(); 
    byte[] myEventItemsArray = GetEventItemByteArrayFromDatabase(); 
    uint numEvents = 1000; 
    uint numEventItems = 1000; 

    Stopwatch sw1 = Stopwatch.StartNew(); 
    TestFunction(ref myEventArray, numEvents, ref myEventItemsArray, numEventItems); 
    sw1.Stop(); 

    float timeTakenInSeconds = (float)sw2.ElapsedTicks/Stopwatch.Frequency; 
    Console.WriteLine("Total time: " + timeTakenInSeconds + " seconds. "); 
} 

static void TestFunction(ref byte[] EventArray, uint numEvents, ref byte[] EventItemArray, uint numEventItems) 
{ 
     Calculator calc = new Calculator(); 
     calc.Test(EventArray, numEvents, EventItemArray, numEventItems); 
} 

我运行这个,得到大约0.2秒的时间。 现在考虑这个:

static void Main(string[] args) 
{ 
    byte[] myEventArray = GetEventByteArrayFromDatabase(); 
    byte[] myEventItemsArray = GetEventItemByteArrayFromDatabase(); 
    uint numEvents = 1000; 
    uint numEventItems = 1000; 

    Stopwatch sw1 = Stopwatch.StartNew(); 
    Calculator calc = new Calculator(); 
    calc.Test(myEventArray , numEvents, myEventItemsArray , numEventItems); 
    sw1.Stop(); 

    float timeTakenInSeconds = (float)sw1.ElapsedTicks/Stopwatch.Frequency; 
    Console.WriteLine("Total time: " + timeTakenInSeconds + " seconds. "); 
} 

我运行,并得到了类似的结果,正如人们所期望的那样。 最后,检查了这一点:

static void Main(string[] args) 
{ 
    byte[] myEventArray = GetEventByteArrayFromDatabase(); 
    byte[] myEventItemsArray = GetEventItemByteArrayFromDatabase(); 
    uint numEvents = 1000; 
    uint numEventItems = 1000; 

    TestFunction(ref myEventArray, numEvents, ref myEventItemsArray, numEventItems); 
} 

static void TestFunction(ref byte[] EventArray, uint numEvents, ref byte[] EventItemArray, uint numEventItems) 
{ 
    Stopwatch sw1 = Stopwatch.StartNew(); 
    Calculator calc = new Calculator(); 
    calc.Test(EventArray, numEvents, EventItemArray, numEventItems); 
    sw1.Stop(); 

    float timeTakenInSeconds = (float)sw1.ElapsedTicks/Stopwatch.Frequency; 
    Console.WriteLine("Total time: " + timeTakenInSeconds + " seconds. "); 
} 

当我运行,时序结果是由于某种原因一直快十倍。 任何想法,为什么会是这种情况?

更多信息: Calculator类是在C++/CLI中定义的。我将它用作最终适用于字节数组的本地C++代码的包装。 我也在编译“不安全”的编译器标志。不知道这可能会有什么影响。 所有代码均以发布模式编译。

+2

您是在调试还是发布中运行此代码?此外,它看起来像你正在计时不同的方法。 'TestFunction'接受'ref'参数,而'Test'不接受。 –

+0

如果您激活两个StopWatches会发生什么? (在TestFunction()内部和Main()内) – DrKoch

+0

检查'sw1'与'sw2'(你以不幸的方式混淆了这些名字) – DrKoch

回答

2

我发现原因。这是因为在第一种情况下,我的计算器对象的创建包含在计时结果中,而在第三种情况下则没有。

如果我理解正确, 堆栈变量实际上并没有在您输入“new()”的行上创建,编译器会将内存分配移动到方法“prolog”。

看到这个页面:https://msdn.microsoft.com/en-us/library/tawsa7cb.aspx

“如果需要的序言保存参数寄存器在他们的家庭住址,推动栈上非易失性寄存器,分配堆栈的固定部分为当地人和临时,以及可选建立一个帧指针“。所以我的“案例1”包括“新”(因为它发生在TestFunction的序言中),“案例3”排除了它,因为“新”已经发生了。

+0

有趣。我认为实际的分配将是这里表现最大的一次。 – aevitas

+0

实际分配是最大的打击 - 它只是没有发生在我认为的地方。 – Japes55

相关问题