C# 精准計時之 QueryPerformanceCounter QueryPerformanceFrequency用法


C# 用法:

    public static class QueryPerformanceMethd
    {
        [DllImport("kernel32.dll")]
      public  extern static short QueryPerformanceCounter(ref long x);


        [DllImport("kernel32.dll")]
        public extern static short QueryPerformanceFrequency(ref long x);
    }

 

    static void Main(string[] args) { long stop_Value = 0; long start_Value = 0; long freq = 0; QueryPerformanceMethd.QueryPerformanceFrequency(ref freq); QueryPerformanceMethd.QueryPerformanceCounter(ref start_Value); //Fun() 需要計時方法 QueryPerformanceMethd.QueryPerformanceCounter(ref stop_Value); double time = (double)(stop_Value - start_Value) / (double)(freq); Console.WriteLine(time);//單位S  Console.ReadLine(); } 

計算所得time即為fun()方法所消耗時間。

 

 

C++中QueryPerformanceCounter  QueryPerformanceFrequency的用法

#include "stdafx.h"
#include "windows.h"


void main()
{
    LARGE_INTEGER nFreq;
    LARGE_INTEGER nBeginTime;
    LARGE_INTEGER nEndTime;
    double time;
    QueryPerformanceFrequency(&nFreq);
    QueryPerformanceCounter(&nBeginTime);
    Sleep(1000);
    QueryPerformanceCounter(&nEndTime);
    time = (double)(nEndTime.QuadPart - nBeginTime.QuadPart) / (double)nFreq.QuadPart;
    printf("%f\n", time);
    system("Pause");
}

計算Sleep(1000)所消耗的精確時間,並非精確的1s

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM