c#中使用Stopwatch工具类统计程序运行时间,精确度微秒
2021/4/30 12:28:11
本文主要是介绍c#中使用Stopwatch工具类统计程序运行时间,精确度微秒,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
c#统计程序运行时间方法
c#中stpwth的ElapsedTicks是程序执行的时钟滴答。
通过获取工具类的频率Frequency来计算与真实时间的比值。
通过这个比值得到真实的时间
下面是时钟滴答与微妙us的比值计算方法。
double usRatio = (double)(1000 * 1000) / Stopwatch.Frequency;
public class statisticsTest{ // 统计时间要用的工具 private Stopwatch stpwth; // 存储每次统计的时间 private List<long> rtt_time; private long rtt_average; void statisticsTime_start() { stpwth.Reset(); stpwth.Start(); } // 返回的是us long statisticsTime_finish() { stpwth.Stop(); UnityEngine.Debug.Log("Time ElapsedTicks:" + stpwth.ElapsedTicks); double usRatio = (double)(1000 * 1000) / Stopwatch.Frequency; //UnityEngine.Debug.Log("Time ElapsedMilliseconds:" + stpwth.ElapsedMilliseconds); //UnityEngine.Debug.Log("Time Elapsed:" + stpwth.Elapsed); //UnityEngine.Debug.Log("Time Frequency:" + Stopwatch.Frequency); //UnityEngine.Debug.Log("Time IsHighResolution:" + Stopwatch.IsHighResolution); return (long)(stpwth.ElapsedTicks * usRatio); } void statisticsFun() { rtt_time.Sort(); long sum = 0; // 去掉最高值和最低值 for (int i = 1; i < rtt_time.Count - 1; ++i) { UnityEngine.Debug.Log("Rtt_time[" + i + "] = " + rtt_time[i]); sum += rtt_time[i]; } // 去掉最高值和最低值, 在除以2求单程 rtt_average = (sum / (rtt_time.Count - 2) / 2); UnityEngine.Debug.Log("Rtt_time average: " + rtt_average + "μs"); } void Start(){ stpwth = new Stopwatch(); rtt_time = new List<long>(); } void Test(){ // 统计开始 statisticsTime_start(); // 中间要防止的运行程序 int i = 1000000; while(--i); // 获取统计时间 rtt_time.Add(statisticsTime_finish()); // 可以给时间进行排个序 statisticsFun(); } }
这篇关于c#中使用Stopwatch工具类统计程序运行时间,精确度微秒的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用
- 2024-01-23.NET开源的简单、快速、强大的前后端分离后台权限管理系统