【发布时间】:2015-05-04 23:04:07
【问题描述】:
我在我的 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. ");
}
当我运行 that 时,由于某种原因,计时结果始终快十倍。 任何想法为什么会这样?
更多信息: Calculator 类在 C++/CLI 中定义。我将它用作最终与字节数组一起使用的本机 C++ 代码的包装器。 我也在使用“不安全”编译器标志进行编译。不确定这是否会产生任何影响。 所有代码都在发布模式下编译。
【问题讨论】:
-
您是在调试还是发布中运行此代码?此外,看起来你正在计时不同的方法。
TestFunction采用ref参数,而Test没有。 -
如果同时激活两个秒表会怎样? (在 TestFunction() 内部和 Main() 内部)
-
检查
sw1与sw2(不幸的是,您将这些名称混为一谈) -
抱歉,sw1/sw2 是错字。修好了。
-
能否尝试在你的计时代码前调用Calculator.Test,让计时时方法已经被JIT编译?