zoukankan      html  css  js  c++  java
  • C#计算一段程序运行时间的三种方法

    第一种方法利用System.DateTime.Now:

    static void SubTest()
    { 
      DateTime beforDT = System.DateTime.Now; 
    
      //耗时巨大的代码 
    
      DateTime afterDT = System.DateTime.Now; 
      TimeSpan ts = afterDT.Subtract(beforDT); 
      Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds); 
    }

    第二种用Stopwatch类(System.Diagnostics):

    static void SubTest()
    { 
      Stopwatch sw = new Stopwatch(); 
      sw.Start(); 
    
      //耗时巨大的代码 
    
      sw.Stop(); 
      TimeSpan ts2 = sw.Elapsed; 
      Console.WriteLine("Stopwatch总共花费{0}ms.", ts2.TotalMilliseconds); 
    }

    第三种用API实现:

    [System.Runtime.InteropServices.DllImport("Kernel32.dll")] 
    static extern bool QueryPerformanceCounter(ref long count); 
    [System.Runtime.InteropServices.DllImport("Kernel32.dll")] 
    static extern bool QueryPerformanceFrequency(ref long count); 
    static void SubTest()
    { 
      long count = 0; 
      long count1 = 0; 
      long freq = 0; 
      double result = 0; 
      QueryPerformanceFrequency(ref freq); 
      QueryPerformanceCounter(ref count); 
    
      //耗时巨大的代码 
    
      QueryPerformanceCounter(ref count1); 
      count = count1 - count; 
      result = (double)(count) / (double)freq; 
      Console.WriteLine("QueryPerformanceCounter耗时: {0} 秒", result); 
    }
    

    也可以使用委托对其进行封装,方便调用:

         /// <summary>
            /// 计算时间
            /// </summary>
            /// <param name="function">要被执行的代码</param>
            /// <returns>执行这一段代码耗时,单位:毫秒</returns>
            public static string Stopwatch(Action function)
            {
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();
    
                //开始执行业务代码
                function();
    
                sw.Stop();
                TimeSpan timeSpan = sw.Elapsed;
    
                return (timeSpan.TotalMilliseconds) + "ms";
            }
    

      

    作  者:大師兄丶
    出  处:http://www.cnblogs.com/zhao-yi
    Git 地 址:https://github.com/ZhaoYis
    个人博客:http://www.zhaoyis.com.cn
    关于作者:主要从事基于.Net Framework平台的项目开发。如有问题或建议,请多多赐教!
    版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
    声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是作者坚持原创和持续写作的最大动力!
  • 相关阅读:
    晓歌:全球金融危机十周年,下一场金融危机不可避免且更惨烈?
    要让孩字喜欢上错误,但不是喜欢出错
    RSA 加密原理
    《道德经》里的“道”和“德”到底是什么意思?
    利用大数据做好消费者运营,你该了解这些
    世界上最著名的操作系统是用什么语言编写的?
    一篇文章带你快速弄清楚什么是终端
    一篇文章看清楚 Linux 的职业发展方向
    微软:悬赏10万美金破解 Linux 系统
    2020年你最需要掌握的11种编程语言
  • 原文地址:https://www.cnblogs.com/zhao-yi/p/6225962.html
Copyright © 2011-2022 走看看