C# timer function (milliseconds)

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

class Program
{
    // Call API function 
    [DllImport( " kernel32.dll " )]
     extern  static  short QueryPerformanceCounter( ref  long x);
    [DllImport("kernel32.dll")]
    extern static short QueryPerformanceFrequency(ref long x);

    static void Main(string[] args)
    {
        // Method 1 
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(1000);
        stopWatch.Stop();
        long times1 = stopWatch.ElapsedMilliseconds; 
        Console.WriteLine("RunTime " + times1);


        // 方法二
        long stop_Value = 0;
        long start_Value = 0;
        long freq = 0;
        QueryPerformanceFrequency( ref freq);   // Get the CPU frequency 

        QueryPerformanceCounter( ref start_Value); // Get the initial pre-value 
        Thread.Sleep( 1000 );
        QueryPerformanceCounter( ref stop_Value); // Get the stop variable value 
        var times2 = (stop_Value - start_Value) / ( double )freq * 1000 ;
        Console.WriteLine("RunTime " + times2);
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325014180&siteId=291194637