C#的中stopwatch的简单应用

本文主要是讲解stopwatch对程序运行时间的准确测量

仅仅介绍里面的StartNew()方法,Restart()方法和ElapsedMilliseconds { get;}属性

public void StartNew():作用是对新的 System.Diagnostics.Stopwatch 实例进行初始化,将运行时间属性设置为零,然后开始测量运行时间。
它的返回结果是刚刚开始python基础教程测量运行时间的System.Diagnostics.Stopwatch。
public void Restart():作用是停止时间间隔测量,将运行时间重置为零,然后开始测量运行时间。
public long ElapsedMilliseconds { get;}:作用是获取当前实例测量得出的总运行时间(以毫秒为单位)。
返回结果:一个只读长c#教程整型,表示当前实例测量得出的总毫秒数
注意:在使用stopwatch时,命名空间需要引用using System.Diagnostics

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Diagnostics;
using System.Threading;

namespace SynchronizationProblems
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 0;
            const int iterationNumber = 5000000;
            Stopwatch sw = Stopwatch.StartNew();
            for(int i=0;i<iterationNumber;i++)
            {
                x++;
            }
            Console.WriteLine("不使用锁的情况下花费的时间:{0}ms",sw.ElapsedMilliseconds);
            sw.Restart();

            for (int i = 0; i < iterationNumber; i++)
            {
                Interlocked.Increment(ref x);
            }

            Console.WriteLine("使用锁的情况下花费的时间:{0}ms", sw.ElapsedMilliseconds);
            Console.Read();

        }
    }
}

运行环境是VS2017,运行结果为:

在这里插入图片描述

参考内容:
博客:https://www.cnblogs.com/vaevvaev/p/6929967.html
书籍:Learning hard C#学习笔记 (李志著)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值