我注意到启动时间会因此而有所不同,因此我放置了一段初始化代码。我觉得这很奇怪,所以我写了一个小基准,证实了我的怀疑。看来在调用main方法之前执行的代码比正常情况慢。静态构造函数中的代码运行速度较慢
为什么Benchmark();
以不同的速度运行,取决于在常规代码路径之前和之后调用?
这里的基准代码:
class Program {
static Stopwatch stopwatch = new Stopwatch();
static Program program = new Program();
static void Main() {
Console.WriteLine("main method:");
Benchmark();
Console.WriteLine();
new Program();
}
static Program() {
Console.WriteLine("static constructor:");
Benchmark();
Console.WriteLine();
}
public Program() {
Console.WriteLine("public constructor:");
Benchmark();
Console.WriteLine();
}
static void Benchmark() {
for (int t = 0; t < 5; t++) {
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
IsPrime(2 * i + 1);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds + " ms");
}
}
static Boolean IsPrime(int x) {
if ((x & 1) == 0)
return x == 2;
if (x < 2)
return false;
for (int i = 3, s = (int)Math.Sqrt(x); i <= s; i += 2)
if (x % i == 0)
return false;
return true;
}
}
结果表明:Benchmark()
运行几乎两倍两个静态构造函数和构造函数static Program program
财产慢:
// static Program program = new Program()
public constructor:
894 ms
895 ms
887 ms
884 ms
883 ms
static constructor:
880 ms
872 ms
876 ms
876 ms
872 ms
main method:
426 ms
428 ms
426 ms
426 ms
426 ms
// new Program() in Main()
public constructor:
426 ms
427 ms
426 ms
426 ms
426 ms
倍增迭代的次数基准循环会使所有时间翻倍,这表明所发生的性能损失不是恒定的,而是一个因素。
// static Program program = new Program()
public constructor:
2039 ms
2024 ms
2020 ms
2019 ms
2013 ms
static constructor:
2019 ms
2028 ms
2019 ms
2021 ms
2020 ms
main method:
1120 ms
1120 ms
1119 ms
1120 ms
1120 ms
// new Program() in Main()
public constructor:
1120 ms
1128 ms
1124 ms
1120 ms
1122 ms
为什么会这样呢?这将是有意义的,如果初始化如果它完成它所属的地方一样快。测试是在.NET 4,发布模式,优化。
究竟是什么问题? – jcolebrand 2012-07-13 03:17:08
编译设置?框架版本? – user7116 2012-07-13 03:24:41
请看看我的编辑是否让你感觉(我不知道为什么),试着在.Net 4/release上得到类似的结果。 – 2012-07-13 03:52:17