我在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++代码的包装。 我也在编译“不安全”的编译器标志。不知道这可能会有什么影响。 所有代码均以发布模式编译。
您是在调试还是发布中运行此代码?此外,它看起来像你正在计时不同的方法。 'TestFunction'接受'ref'参数,而'Test'不接受。 –
如果您激活两个StopWatches会发生什么? (在TestFunction()内部和Main()内) – DrKoch
检查'sw1'与'sw2'(你以不幸的方式混淆了这些名字) – DrKoch