引言
偶然发现c# 的计时器类stopwatch,他特别适合测量运行时间,使用简单、计时精确。它源于命名空间system.diagnostics,使用时必须using引用。
经典举例
下面用一秒延时的实例来创建一个最简单的实例。
(1)启动和停止方法实例
//按键单击
private void button_watch_click(object sender, eventargs e)
{
console.writeline("action_spent_time:" + watch(action));
}
//模拟用户函数耗时
private void action()
{
thread.sleep(1000);
}
//开始和停止定时器
public static double watch(action action)
{
//实例化
stopwatch stopwatch = new stopwatch();
//启动定时器
stopwatch.start();
//用户任务
action();
//停止定时器
stopwatch.stop();
//返回计时器时间
return stopwatch.elapsed.totalmilliseconds;
}
打印显示
action_spent_time:1014.7956
(2)复位和重启方法实例
//按键单击
private void button_watch_click(object sender, eventargs e)
{
watchresetandrestart(action);
}
//模拟用户函数耗时
private void action()
{
thread.sleep(1000);
}
//复位和重启计时器时器
public void watchresetandrestart(action action)
{
//实例化
stopwatch stopwatch = new stopwatch();
//启动定时器
stopwatch.start();
//用户任务
action();
console.writeline("action:"+ stopwatch.elapsed.totalmilliseconds);
//复位定时器
stopwatch.reset();
console.writeline("action reset:" + stopwatch.elapsed.totalmilliseconds);
//重启定时器
stopwatch.restart();
//用户任务
action();
console.writeline("action restart:" + stopwatch.elapsed.totalmilliseconds);
//复位定时器
stopwatch.reset();
}
}
打印显示:
action:1000.8485
action reset:0
action restart:1009.2571
小结
是不是觉得很简单。小伙伴们可以用起来。
1、实例中可以看到精度可以得到0.1微秒使用double类型,我认为算精度很高的吧,不需要这么高精度可以做运算舍去,或者使用其它的更低精度的属性,如stopwatch.elapsedmilliseconds等。
2、复位reset()和停止stop()的功能都停止了计时器,但是reset,将时间复位为0了,这里注意一下就好。
到此这篇关于c#中高精度计时器stopwatch的用法详解的文章就介绍到这了,更多相关c# stopwatch内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论