数据结构和算法 – 番外篇.时间测试类Timing

时间:2023-03-09 15:03:05
数据结构和算法 – 番外篇.时间测试类Timing
public class Timing
{
//startingTime--用来存储正在测试的代码的开始时间。
TimeSpan startingTime;
//duration——用来存储正在测试的代码的终止时间。
TimeSpan durantion;
public Timing()
{
startingTime = new TimeSpan(0);
durantion = new TimeSpan(0);
} public void startTime()
{
//先强制对所有代码进行回收
GC.Collect();
//挂起当前线程,直到处理终结器队列的线程清空该队列为止
GC.WaitForPendingFinalizers();
//获取关联程序运行代码所用的时间
startingTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
} public void StopTime()
{
durantion = Process.GetCurrentProcess().Threads[0].
UserProcessorTime.Subtract(startingTime);
} public TimeSpan Result()
{
return durantion;
}
}

 

 

 

测试

static void Main(string[] args)
{
//DateTime starttime = DateTime.Now;
//Print(10000);
////PrintN(100000);
//DateTime endtime = DateTime.Now; //double end = TimeHelp.Service.Timehelp(starttime, endtime);
//Console.WriteLine("耗时:" + end); Timing tObj = new Timing();
tObj.startTime();
Print(500000);
tObj.StopTime();
Console.WriteLine("耗时:" + tObj.Result().TotalSeconds);
Console.Read();
} public static void Print(int N)
{
for (int i = 0; i <= N; i++)
{
Console.WriteLine(i);
}
return;
}