1. 利用System.Diagnostics.StopWatch:
代码
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
const int c_ExecutionCount = 1000000;
for (int i = 0; i < c_ExecutionCount; i++)
{
var obj = Factory<MyClass1>.Create(i);
//var obj = ReflectionFactory<MyClass1>(i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds + "ms");
}
{
Stopwatch sw = new Stopwatch();
sw.Start();
const int c_ExecutionCount = 1000000;
for (int i = 0; i < c_ExecutionCount; i++)
{
var obj = Factory<MyClass1>.Create(i);
//var obj = ReflectionFactory<MyClass1>(i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds + "ms");
}
2. 利用Thread的UserProcessorTime:
在.net环 境中,需要考虑程序运行所处的线程以及无用单元收集可能在任何时候发生的事实。所以在编写时间测试代码时需要考虑这些情况。在程序执行过程中无用单元收集可能会发生在任何时候。用 GC.WaitForPendingFinalizers()解决; 在.net环 境中,程序运行在被称为应用程序域的进程中Process类拥有的方法允许操作系统选取当前的进程 (程序运行其内的进程),以及选取存储线程开始执行时间的计时器。
代码
class Timing
{
TimeSpan duration;
public Timing()
{
duration =new TimeSpan(0);
}
public void stopTime()
{
duration =Process.GetCurrentProcess().TotalProcessorTime;
}
public void startTime()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
public TimeSpan Result()
{
return duration;
}
}
class chapter1
{
static void Main()
{
int[] nums = new int[100000];
BuildArray(nums);
Timing tobj = new Timing();
tobj.startTime();
DisplayNums(nums);
tobj.stopTime();
Console.WriteLine("Time: " + tobj.Result().TotalSeconds);
}
static void BuildArray(int[] arr)
{
for (int i = 0; i <= 99999; i++)
arr[i] = i;
}
static void DisplayNums(int[] arr)
{
for (int i = 0; i <= arr.GetUpperBound(0); i++)
Console.WriteLine(arr[i] + "");
}
}
{
TimeSpan duration;
public Timing()
{
duration =new TimeSpan(0);
}
public void stopTime()
{
duration =Process.GetCurrentProcess().TotalProcessorTime;
}
public void startTime()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
public TimeSpan Result()
{
return duration;
}
}
class chapter1
{
static void Main()
{
int[] nums = new int[100000];
BuildArray(nums);
Timing tobj = new Timing();
tobj.startTime();
DisplayNums(nums);
tobj.stopTime();
Console.WriteLine("Time: " + tobj.Result().TotalSeconds);
}
static void BuildArray(int[] arr)
{
for (int i = 0; i <= 99999; i++)
arr[i] = i;
}
static void DisplayNums(int[] arr)
{
for (int i = 0; i <= arr.GetUpperBound(0); i++)
Console.WriteLine(arr[i] + "");
}
}