码迷,mamicode.com
首页 > Windows程序 > 详细

C# 精准计时之 QueryPerformanceCounter QueryPerformanceFrequency用法

时间:2016-05-11 21:57:42      阅读:971      评论:0      收藏:0      [点我收藏+]

标签:

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

 

C# 精准计时之 QueryPerformanceCounter QueryPerformanceFrequency用法

标签:

原文地址:http://www.cnblogs.com/Van-Bumblebee/p/5483432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!