只是爲了進一步重申重要的性能測試如何我跑在Windows 7與2010年靶向.NET 4.0 VS編譯64位本地和32位模式下我的核心i5-750下面的測試,得到了以下結果:
public static bool DoSomething(double[] args) {
bool ret = false;
for (int i = 0; i < args.Length; i++) {
if (double.IsNaN(args[i])) {
ret = !ret;
}
}
return ret;
}
public static bool DoSomething2(double[] args) {
bool ret = false;
for (int i = 0; i < args.Length; i++) {
if (args[i] != args[i]) {
ret = !ret;
}
}
return ret;
}
public static IEnumerable<R> Generate<R>(Func<R> func, int num) {
for (int i = 0; i < num; i++) {
yield return func();
}
}
static void Main(string[] args) {
Random r = new Random();
double[] data = Generate(() => {
var res = r.NextDouble();
return res < 0.5 ? res : Double.NaN;
}, 1000000).ToArray();
Stopwatch sw = new Stopwatch();
sw.Start();
DoSomething(data);
Console.WriteLine(sw.ElapsedTicks);
sw.Reset();
sw.Start();
DoSomething2(data);
Console.WriteLine(sw.ElapsedTicks);
Console.ReadKey();
}
在86模式(釋放,天然地):
DoSomething() = 139544
DoSomething2() = 137924
在x64的模式:
DoSomething() = 19417
DoSomething2() = 17448
但是,如果我們的NaN
的分佈更稀疏,會發生一些有趣的事情。如果我們改變我們的0.5
常數0.9
(只有10%NaN的),我們得到:
86:
DoSomething() = 31483
DoSomething2() = 31731
64:
DoSomething() = 31432
DoSomething2() = 31513
重新排序的電話顯示了相同的趨勢,以及。食物的思想。
double.isNan實際上是一個小函數......所以,正如你所指出的,有一個開銷叫它。 – Hbas 2010-07-20 02:35:47
在公共中間語言(CIL)它有7行的代碼: L_0000:ldarg.0 L_0001:ldarg.0 L_0002:beq.s L_0006 L_0004:ldc.i4.1 L_0005:滯留 L_0006 :ldc.i4.0 L_0007:ret – Hbas 2010-07-20 02:48:14