首页 > 学院 > 开发设计 > 正文

【Visual Studio】Stopwatch类计算程序运行所需时间

2019-11-11 05:09:28
字体:
来源:转载
供稿:网友

应用场景

  我们知道,很多时候,一个功能,我们可以给出多种实现方法。那么到底哪个实现代码更快速呢?为了判断代码的响应时间,我们就需要用到Stopwatch类了。Stopwatch类提供了一组方法和属性,可用于准确地测量运行时间。命名空间:System.Diagnostics。

实例演示

PRivate void button2_Click(object sender, EventArgs e){ Stopwatch stopWatch = new Stopwatch(); //实例化一个Stopwatch对象 stopWatch.Start(); //开始时间检测 Thread.Sleep(10000); //测试代码 stopWatch.Stop(); //结束时间检测 // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; //运行时间 // Format and display the TimeSpan value. string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); MessageBox.Show("RunTime " + elapsedTime);}

效果图

这里写图片描述

参考资料:Microsoft文档


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表