当前位置: 代码网 > it编程>编程语言>C# > C#中高精度计时器Stopwatch的用法详解

C#中高精度计时器Stopwatch的用法详解

2024年11月25日 C# 我要评论
引言偶然发现c# 的计时器类stopwatch,他特别适合测量运行时间,使用简单、计时精确。它源于命名空间system.diagnostics,使用时必须using引用。经典举例下面用一秒延时的实例来

引言

偶然发现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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com