C# Stopwatch类_性能_时间计时器

文章只含部分属性方法等,有想了解全面的在下面链接中可以查看:.NET API browser

Stopwatch 类 (System.Diagnostics) | Microsoft Learn

一、什么是Stopwatch

Stopwatch:提供一组方法和属性,可以准确的测量运行时间。使用的时候需要引用命名空间:System.Diagnostics。

二、Stopwatch的简单使用

cs 复制代码
//创建Stopwatch实例
Stopwatch sw = new Stopwatch();
//开始计时
sw.Start();
for (int i = 0; i < 100; i++)
{
  Console.WriteLine(i);
}
//停止计时
sw.Stop();
Console.WriteLine("用时:" + sw.ElapsedMilliseconds + "");
//重置 停止时间间隔测量,并将运行时间重置为0
sw.Reset();
Console.WriteLine("用时:" + sw.ElapsedMilliseconds + "");
//重启 停止时间间隔测量,并将运行时间重置为0,然后重新开始测量运行时间
sw.Restart();
for (int i = 0; i < 100; i++)
{
  Console.WriteLine(i);
}
sw.Stop();
//获取当前实例测量得出的总运行时间(以毫秒为单位)
Console.WriteLine("用时:" + sw.ElapsedMilliseconds + "");
//获取当前实例测量得出的总运行时间
Console.WriteLine("用时:"+sw.Elapsed); 
//获取当前实例测量得出的总运行时间(用计时器刻度表示)。
Console.WriteLine(sw.ElapsedTicks);
Console.Read();
//使用StartNew,相当于已经实例化并且启动计时
Stopwatch sw=Stopwatch.StartNew();
for (int i = 0; i < 100; i++)
{
  Console.WriteLine(i);
}
sw.Stop();
//获取当前实例测量得出的总运行时间(以毫秒为单位)
Console.WriteLine("用时:" + sw.ElapsedMilliseconds + "");
//获取当前实例测量得出的总运行时间
Console.WriteLine("用时:"+sw.Elapsed); 
Console.Read();

原文链接:https://blog.csdn.net/TheWindofFate/article/details/122882621

相关推荐
hez20101 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉6 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫8 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫8 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6259 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902119 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠9 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫11 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech12 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf13 天前
C#摸鱼实录——IoC与DI案例详解
c#