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工具类统计程序运行时间,精确度微秒的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程