获取代码运行时间

1.使用Stopwatch

 //实例化一个计时器
Stopwatch watch = new Stopwatch();
//开始计时
watch.Start();

//此处为要计算的运行代码
for (int i = 1; i < 1000000; i++) { }   // Execute the task to be timed

//结束计时
watch.Stop();

//获取当前实例测量得出的总运行时间(以毫秒为单位)
string time = watch.ElapsedMilliseconds.ToString();
//说明:Stopwatch提供了几个方法用以控制Stopwatch对象。Start方法开始一个计时操作,Stop方法停止计时。为避免这种情况,在第二次计时前用Reset方法将对象归零
 
Console.WriteLine("Elapsed: {0}",watch.Elapsed);
Console.WriteLine("In milliseconds: {0}",watch.ElapsedMilliseconds);
Console.WriteLine("In timer ticks: {0}",watch.ElapsedTicks);

2.使用DateTime

DateTime startTime = DateTime.Now;
Console.WriteLine ("Started: {0}", startTime);
 
// Execute the task to be timed
for (int i=1; i < 100000; i++){}  

DateTime stopTime = DateTime.Now;
Console.WriteLine ("Stopped: {0}", stopTime);

TimeSpan elapsedTime = stopTime - startTime;
Console.WriteLine ("Elapsed: {0}", elapsedTime);
Console.WriteLine ("in hours       :" + elapsedTime.TotalHours);
Console.WriteLine ("in minutes     :" + elapsedTime.TotalMinutes);
Console.WriteLine ("in seconds     :" + elapsedTime.TotalSeconds);
Console.WriteLine ("in milliseconds:" + elapsedTime.TotalMilliseconds);

3.调用API

[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
static extern bool QueryPerformanceCounter(ref long count);
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
static extern bool QueryPerformanceFrequency(ref long count);
static void SubTest()
{
    long count = 0;
    long count1 = 0;
    long freq = 0;
    double result = 0;
    QueryPerformanceFrequency(ref freq);
    QueryPerformanceCounter(ref count);

    for (int i = 0; i < int.MaxValue; i++)
    { }

    QueryPerformanceCounter(ref count1);
    count = count1 - count;
    result = (double)(count) / (double)freq;
    Console.WriteLine("QueryPerformanceCounter Time: {0} s", result);
    Console.ReadKey();
}

4.利用Thread的UserProcessorTime

class Program
{
    static void Main(string[] args)
    {
        Timing tobj = new Timing();
        tobj.startTime();
        for (int i = 0; i < int.MaxValue; i++)
        { }
        tobj.stopTime();
        Console.WriteLine("Time: " + tobj.Result().TotalSeconds);
        Console.ReadKey();
    }
}

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;
    }
}
原文地址:https://www.cnblogs.com/jizhiqiliao/p/9993046.html