博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
统计代码执行时间,使用Stopwatch和UserProcessorTime的区别
阅读量:4597 次
发布时间:2019-06-09

本文共 1782 字,大约阅读时间需要 5 分钟。

当我们需要统计一段代码的执行时间,首先想到的可能是Stopwatch类。在这里,先暂不使用Stopwatch,自定义一个统计代码执行时间的类,大致需要考虑到:

1、确保统计的是当前进程、当前线程中代码的执行时间。

2、在统计执行过程中,不允许有垃圾回收。即在统计代码执行时间之前,就让GC完成垃圾回收。

 

举例:统计显示一个数组元素所消耗的时间

 
class Program
{
static void Main(string[] args)
{
int[] arrs = new int[10000];
BuildArray(arrs);
 
CalculateTiming calculateTiming = new CalculateTiming();
calculateTiming.Start();
DisplaySomeDigits(arrs);
calculateTiming.Stop();
 
Console.WriteLine("所耗费时间为:" + calculateTiming.Result().TotalMilliseconds + "毫秒");
}
 
//显示数组元素
static void DisplaySomeDigits(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
}
 
//创建数组
static void BuildArray(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = i;
}
}
}
 
/// 
/// 计算CPU消耗时间
/// 
public class CalculateTiming
{
private TimeSpan startTime;
private TimeSpan duration;
 
public CalculateTiming()
{
startTime = new TimeSpan(0);
duration = new TimeSpan(0);
}
 
public void Start()
{
//手动执行垃圾回收
GC.Collect();
 
//挂起当前线程,直到使用GC对所有托管堆上的对象实施Finalize方法
GC.WaitForPendingFinalizers();
 
//获取当前进程、当前线程执行的起始时间
startTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
}
 
public void Stop()
{
//获取当前进程、当前线程执行所消耗的时间
duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startTime);
}
 
public TimeSpan Result()
{
return duration;
}
}
 
 

以上,通过当前进程、当前线程的UserProcessorTime属性来统计代码执行时间。

如果使用Stopwatch来统计代码执行时间。

 
static void Main(string[] args)
{
int[] arrs = new int[10000];
BuildArray(arrs);
 
Stopwatch sw = new Stopwatch();
sw.Start();
DisplaySomeDigits(arrs);
sw.Stop();
 
Console.WriteLine("所耗费时间为:" + sw.ElapsedMilliseconds + "毫秒");
 
}
 

 

为什么使用Stopwatch统计代码执行时间,耗费时间更长呢?

--使用UserProcessorTime属性来统计,统计的是当前进程、当前线程所消耗的CPU执行时间。而Stopwatch统计的代码执行时间,不仅包括了CPU的执行时间,还包括了在电脑屏幕上显示字符串所占用的I/0时间。

转载于:https://www.cnblogs.com/darrenji/p/4023197.html

你可能感兴趣的文章
STM8S——Universal asynchronous receiver transmitter (UART)
查看>>
Flink - state管理
查看>>
Apache Kafka - KIP-42: Add Producer and Consumer Interceptors
查看>>
ArcGIS JS Demo
查看>>
webservice发布问题,部署iis后调用不成功
查看>>
Koch 分形,海岸线,雪花
查看>>
ubuntu系统下Python虚拟环境的安装和使用
查看>>
IOS7开发~新UI学起(二)
查看>>
软件过程度量和CMMI模型概述
查看>>
数据结构(DataStructure)与算法(Algorithm)、STL应用
查看>>
Linux与Windows xp操作系统启动过程
查看>>
linux运维、架构之路-Kubernetes1.13离线集群部署双向认证
查看>>
[Leetcode]Substring with Concatenation of All Words
查看>>
Gem install rmagick 报错问题~
查看>>
验证一个方法触发时机
查看>>
25句充满正能量的句子
查看>>
python学习手册笔记——27.更多实例
查看>>
Spring Cloud Alibaba 新版本发布:众多期待内容整合打包加入!
查看>>
Android Camera 使用小结
查看>>
20170908 校内模拟赛 游戏
查看>>