Код:
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine();
int repeatCount = 1000 * 1000 * 1000;
Measure("GetHashCode<T>()", () =>
{
for (int i = 0; i < repeatCount; i++)
{
GetHashCode(i);
}
});
Measure("GetHashCodeStruct<T>()", () =>
{
for (int i = 0; i < repeatCount; i++)
{
GetHashCodeStruct(i);
}
});
Measure("GetHashCodeInt32()", () =>
{
for (int i = 0; i < repeatCount; i++)
{
GetHashCodeInt32(i);
}
});
Measure("int.GetHashCode()", () =>
{
for (int i = 0; i < repeatCount; i++)
{
i.GetHashCode();
}
});
Console.WriteLine();
Console.WriteLine("Done. Press any key to exit.");
Console.ReadKey();
}
private static void Measure(string name, Action callback)
{
Stopwatch sw = Stopwatch.StartNew();
callback();
sw.Stop();
Console.WriteLine("{0,30}: {1:#,0.##} ms", name, sw.ElapsedMilliseconds);
}
private static int GetHashCode<T>(T value)
{
return value == null ? 0 : value.GetHashCode();
}
private static int GetHashCodeStruct<T>(T value) where T: struct
{
return value.GetHashCode();
}
private static int GetHashCodeInt32(int value)
{
return value.GetHashCode();
}
}
}
Попробуйте:
1. Примерно оценить соотношение времени выполнения методов.
2. Объяснить несоответствие между ожидаемым и наблюдаемым результатом
Застрял на п.2
P.S. Предыдущая часть была
вот тутАвтор: Sinix
Дата: 04.03.11
.