c# – 为什么在.NET中检查算术有时比未检查更快?

前端之家收集整理的这篇文章主要介绍了c# – 为什么在.NET中检查算术有时比未检查更快?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么当我打开C#项目属性>下的“检查算术下溢/溢出”时构建>高级,以下代码关闭选项(141毫秒)运行得更快(138毫秒)?

测试运行#1:138ms,带有检查算术,141ms没有

  1. using System;
  2. using System.Diagnostics;
  3.  
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. var s = new Stopwatch();
  9. s.Start();
  10. int a = 0;
  11. for (int i = 0; i < 100000000; i += 3) {
  12. if (i == 1000)
  13. i *= 2;
  14. if (i % 35 == 0)
  15. ++a;
  16. }
  17. s.Stop();
  18. Console.WriteLine(s.ElapsedMilliseconds);
  19. Console.WriteLine(a);
  20. }
  21. }

另一方面,如果您注释掉if(i == 1000)i * = 2;,则检查的代码比未检查的代码(116 ms)运行得慢(120 ms).

测试运行#2:120ms,116ms没有

  1. using System;
  2. using System.Diagnostics;
  3.  
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. var s = new Stopwatch();
  9. s.Start();
  10. int a = 0;
  11. for (int i = 0; i < 100000000; i += 3) {
  12. if (i % 35 == 0)
  13. ++a;
  14. }
  15. s.Stop();
  16. Console.WriteLine(s.ElapsedMilliseconds);
  17. Console.WriteLine(a);
  18. }
  19. }

进程:重复从PowerShell提示符在Visual Studio外部手动运行.exe,直到结果时间戳保持一致(±1 ms);多次在设置之间翻转以确保一致的结果.

测试盒设置:

> Windows 8.1 Pro x64
> VS2013更新2
>英特尔酷睿i7-4500
>默认C#控制台项目模板
>发布配置

解决方法

答案是你正在处理许多常量,这些常量允许JIT做出安全的假设,它永远不会溢出.如果您使用类似Fibbonacci基准的东西,差异就会变得清晰.

2770ms vs 4150ms(Anycpu,32位首选)

  1. using System;
  2. using System.Diagnostics;
  3.  
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. var s = new Stopwatch();
  9. s.Start();
  10. int a = 0;
  11. for (int i = 0; i < 100000000; i++)
  12. {
  13. a = Fibonacci(45);
  14. }
  15. s.Stop();
  16. Console.WriteLine(s.ElapsedMilliseconds);
  17. }
  18.  
  19. public static int Fibonacci(int n)
  20. {
  21. int a = 0;
  22. int b = 1;
  23. for (int i = 0; i < n; i++)
  24. {
  25. int temp = a;
  26. a = b;
  27. // if the JIT compiler is clever,only this one needs to be 'checked'
  28. b = temp + b;
  29. }
  30. return a;
  31. }
  32.  
  33. }

猜你在找的C#相关文章