C# 计时函数(毫秒)

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

class Program
{
    //调用API函数
    [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)
    {
        // 方法一
        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);  //获取CPU频率

        QueryPerformanceCounter(ref start_Value); //获取初始前值
        Thread.Sleep(1000);
        QueryPerformanceCounter(ref stop_Value);//获取终止变量值
        var times2 = (stop_Value - start_Value) / (double)freq * 1000;
        Console.WriteLine("RunTime " + times2);
    }
}

 Stopwatch 通过计算基础计时器机制中的计时器刻度来测量运行时间。 如果已安装的硬件和操作系统支持高分辨率性能计数器,则 Stopwatch 类使用该计数器来测量运行时间。 否则为 Stopwatch 类使用系统计时器来测量运行时间。 使用 Frequency 和 IsHighResolution 字段来确定的精度和解决方法 Stopwatch 计时实现。

posted @ 2018-04-28 16:09  Hello_2018  阅读(3583)  评论(0编辑  收藏  举报