C#中提供的精准测试程序运行时间的类Stopwatch
  TnD0WQEygW8e 2023年11月08日 47 0

 

在需要对程序的执行时间进行精准测试的程序员,不妨使用.Net提供的Stopwatch类,它的命名空间是:System.Diagnostics
代码如下:

using System; 
    using System.Collections.Generic; 
    using System.Text; 
    using System.Diagnostics; 
      
     
    namespace StopWatch 
    { 
        class Program 
        { 
            static void Main(string[] args) 
            { 
                Stopwatch sw = new Stopwatch(); 
                sw.Start(); 
                //这里填写要执行的代码 
               sw.Stop(); 
               Console.WriteLine("总运行时间:" + sw.Elapsed); 
               Console.WriteLine("测量实例得出的总运行时间(毫秒为单位):" + sw.ElapsedMilliseconds); 
                Console.WriteLine("总运行时间(计时器刻度标识):" + sw.ElapsedTicks); 
                Console.WriteLine("计时器是否运行:" + sw.IsRunning.ToString()); 
           } 
        } 
    }

运行结果如下:
总运行时间:00:00:00.0000013
测量实例得出的程序运行时间(毫秒为单位):0
总运行时间(计时器刻度标识):5
计时器是否运行:False

 

using System; 
    using System.Diagnostics;    namespace StopWatchClass 
    { 
        class Program 
        { 
            static void Main(string[] args) 
            { 
                Stopwatch timer = new Stopwatch(); 
                long total = 0;                timer.Start(); 
                for (int i = 1; i <= 10000000; i++) 
                { 
                    total += i; 
                }                timer.Stop();
                decimal micro = timer.Elapsed.Ticks / 10m; 
                Console.WriteLine("Execution time was {0:F1} microseconds.", micro); 
            } 
        } 
    }




【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
TnD0WQEygW8e