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();
}
}