我想通過將代碼放入方法而不是僅僅調用它來測試丟失了多少時間。C#方法 - 比代碼更快地調用
令我驚訝的是,方法調用速度更快,我問自己:爲什麼?
這是代碼: 的HObjects是圖像處理庫「的Halcon」的一部分,並且非常普遍地與「出」的方法調用中使用,所以不要對恐怖的樣子;-)
static void Main(string[] args)
{
int runs = 900000;
HObject hob1;
HObject hob2;
HObject hob3;
HObject hob4;
HObject hob5;
HObject hob6;
DateTime t1 = DateTime.Now;
for (int i = 0; i < runs; i++)
{
doItMethod(out hob1, out hob2, out hob3, out hob4, out hob5, out hob6);
}
TimeSpan ts1 = TimeSpan.FromTicks(DateTime.Now.Ticks - t1.Ticks);
DateTime t2 = DateTime.Now;
for (int i = 0; i < runs; i++)
{
HOperatorSet.GenEmptyObj(out hob1);
HOperatorSet.GenEmptyObj(out hob2);
HOperatorSet.GenEmptyObj(out hob3);
HOperatorSet.GenEmptyObj(out hob4);
HOperatorSet.GenEmptyObj(out hob5);
HOperatorSet.GenEmptyObj(out hob6);
hob1.Dispose();
hob2.Dispose();
hob3.Dispose();
hob4.Dispose();
hob5.Dispose();
hob6.Dispose();
}
TimeSpan ts2 = TimeSpan.FromTicks(DateTime.Now.Ticks - t2.Ticks);
Console.WriteLine("Zeitspanne Methodenaufruf : " + ts1.TotalMilliseconds.ToString());
Console.WriteLine("Zeitspanne direkter Aufruf: " + ts2.TotalMilliseconds.ToString());
Console.ReadKey();
}
static void doItMethod(out HObject hobOut1, out HObject hobOut2, out HObject hobOut3, out HObject hobOut4, out HObject hobOut5, out HObject hobOut6)
{
HOperatorSet.GenEmptyObj(out hobOut1);
HOperatorSet.GenEmptyObj(out hobOut2);
HOperatorSet.GenEmptyObj(out hobOut3);
HOperatorSet.GenEmptyObj(out hobOut4);
HOperatorSet.GenEmptyObj(out hobOut5);
HOperatorSet.GenEmptyObj(out hobOut6);
hobOut1.Dispose();
hobOut2.Dispose();
hobOut3.Dispose();
hobOut4.Dispose();
hobOut5.Dispose();
hobOut6.Dispose();
}
憂
我有一個懷疑:這是一個GC神器。要驗證它,請交換電話:首先測試「direkter AUfruf」(直接呼叫),然後THEN方法調用並重新發布。 –
發現你自己的'Stopwatch'類(http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx)。差異是否相當大(請發佈時間值)?什麼構建你測試過的配置(調試或發佈)? – Dennis
C#編譯器優化代碼,這可能是原因,但您必須使用秒錶類 – opewix