C# 使用StopWatch测量程序运行时间

Stopwatch 实例可以测量⼀个时间间隔的运⾏时间,也可以测量多个时间间隔的总运⾏时间。在典型的 Stopwatch ⽅案中,先调⽤ Start ()⽅法,然后调⽤ Stop() ⽅法,最后使⽤ Elapsed 属性检查运⾏时间。

TimeSpan 值可以表示为 [-]d.hh:mm:ss.ff,其中减号是可选的,它指示负时间间隔,d 分量表示天,hh 表示小时(24 小时制),mm 表示分钟,ss 表示秒,而 ff 为秒的小数部分。即,时间间隔包括整的正负天数、天数和剩余的不足一天的时长,或者只包含不足一天的时长。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace Stopwatch的使用
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //对象实例化
        Stopwatch stopwatch = new Stopwatch();
        private void button1_Click(object sender, EventArgs e)
        {
            //计时器启动
            stopwatch.Start();
            for(int i = 0; i < 800000000;i++)
            {
                int j = 0;
                j = j + 2;   
            }
            //计时器停止
            stopwatch.Stop();
            //判断计时是否正在进行,true为正在进行中
            bool isrunning = stopwatch.IsRunning;
            //获取运行时间 毫秒
            long times1 = stopwatch.ElapsedMilliseconds;

            TimeSpan times2 = stopwatch.Elapsed;
           double days = times2.TotalDays;
            double hours = times2.TotalHours;
            double minutes = times2.TotalMinutes;
            double seconds = times2.TotalSeconds;
           double milliseconds = times2.TotalMilliseconds;

            textBox1.Text += "总运行时间:" + times1 + " 毫秒";
            textBox2.Text += "总运行时间:" + hours + " 小时";
            textBox3.Text += "总运行时间:" + minutes + " 分";
            textBox4.Text += "总运行时间:" + seconds + " 秒";
            textBox5.Text += "总运行时间:" + milliseconds + " 毫秒";

        }
    }
}

 从上图可以看出TimeSpan计时的时间比StopWatch更为精确

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

机器人自动化控制

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值