这是我定义的Timing类
using System;
using System.Diagnostics;
public class Timing
{
TimeSpan startingTime;
TimeSpan duration;
public Timing()
{
startingTime = new TimeSpan(0);
duration = new TimeSpan(0);
}
public void StopTime()
{
duration =Process.GetCurrentProcess().Threads[0].
UserProcessorTime.Subtract(startingTime);
}
public void startTime()
{
GC.Collect();
GC.WaitForPendingFinalizers();
startingTime =
Process.GetCurrentProcess().Threads[0].
UserProcessorTime;
}
public TimeSpan Result()
{
return duration;
}
}
这是Main函数
using System;
using System.Diagnostics;
using System.Threading;
class chapter1
{
static void Main()
{
int[] nums = new int[100000];
BuildArray(nums);
Timing tObj = new Timing();
tObj.startTime();
DisplayNums(nums);
DisplayNums(nums);
DisplayNums(nums);
tObj.StopTime();
Console.WriteLine("time (.NET): " + tObj.Result().TotalSeconds);
Console.ReadKey();
}
static void BuildArray(int[] arr)
{
for (int i = 0; i < 100000; i++)
arr[i] = i;
}
static void DisplayNums(int[] arr)
{
for (int i = 0; i <= arr.GetUpperBound(0); i++)
Console.Write(arr[i] + " ");
}
}
startingTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
这个获得测试的代码的开始时间
duration =Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime);
这个获得测试的代码结束时间与开始时间之差,为什么返回的结果却是0呢?
建议这样计算时间:
1. 将 TimeSpan startingTime; 改为:
Stopwatch sw = new Stopwatch();
2. 将 startingTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime; 改为:
sw.Start();
3. 将 duration =Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime); 改为:
duration = sw.Elapsed.Duration();
我看书上写的是,用这种方法可以避免包含与C#程序同时运行的其他进程所用的时间,所以我感觉还是我给的方法好点,用Process.GetCurrentProcess().TotalSeconds能得出时间但是我不知道我上面写的那个代码为什么得0
@微澜: 看一下tickets是多少?
Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime).Ticks;