MyMSDN

MyMSDN记录开发新知道

计时器代码片段

这不是一个面向对象的代码库,它的存在仅仅只是为了说明几个函数调用,如果要在您的工程中应用相关内容,请自行构建(这应该不难),或者看看我推荐的文档。

// ProcessAffinity.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <vector>

using namespace std;
void DisplayFrequency(ostream &out, LARGE_INTEGER &freq);

struct TimeSpan
{
    LARGE_INTEGER *Frequency;
    LARGE_INTEGER StartCounter;
    LARGE_INTEGER StopCounter;
    BOOL HAS_ERROR;
    double CalTimeSpan(){
        return (StopCounter.QuadPart - StartCounter.QuadPart)/Frequency->QuadPart;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE CurrentProcessHandle;
    DWORD ProcessAffinityMask, SystemAffinityMask, AllowProcessAffinity;

    CurrentProcessHandle = GetCurrentProcess();

    //GetCurrentProcess返回一个常量,代表当前的进程句柄
    cout<<CurrentProcessHandle<<endl;
    cout<<(HANDLE)-1<<endl;
    cout<<(void*)-1<<endl;
    cout<<(void*)0xffffffff<<endl;

    cout<<"-----------------------------"<<endl;

    if(GetProcessAffinityMask(CurrentProcessHandle, &ProcessAffinityMask, &SystemAffinityMask))
    {
        cout<<ProcessAffinityMask<<endl;    //0x0001
        cout<<SystemAffinityMask<<endl;        //0x0001
    
        AllowProcessAffinity = ProcessAffinityMask & SystemAffinityMask;
        cout<<AllowProcessAffinity<<endl;
    }

    LARGE_INTEGER Freq;
    typedef vector<LARGE_INTEGER> FreqVec_type;
    FreqVec_type FreqVec;
    
    while(FreqVec.size() != 5)
    {
        if(QueryPerformanceFrequency(&Freq))
        {
            DisplayFrequency(cout, Freq);
            FreqVec.push_back(Freq);
        }
        Sleep(1000);
    }

    for(FreqVec_type::iterator iter = FreqVec.begin(); iter!=FreqVec.end(); ++iter)
    {
        DisplayFrequency(cout, *iter);
    }

    cout<<"---------------------"<<endl;

    //calculate the timeSpan;
    TimeSpan ts;
    int sleepTime(3123);

    ts.Frequency = &Freq;

    if(QueryPerformanceCounter(&ts.StartCounter))
    {
        ts.HAS_ERROR = false;
        Sleep(sleepTime);
    }
    if(!ts.HAS_ERROR)
    {
        QueryPerformanceCounter(&ts.StopCounter);
    }
    
    cout<<ts.CalTimeSpan()<<endl;
    cout<<(ts.StopCounter.QuadPart-ts.StartCounter.QuadPart)/sleepTime<<endl;

    return 0;
}

void DisplayFrequency(ostream &out, LARGE_INTEGER &freq)
{
    out<<"start display!"<<endl;
    out<<freq.HighPart<<endl;
    out<<freq.LowPart<<endl;
    out<<freq.QuadPart<<endl;
    out<<"end display!"<<endl;
}

推荐文档:《使用增强的计时器测量代码段》(下载可适合打印,已排版,阅读该文档需要使用Microsoft Word 2007或相关阅读器(后缀docx),如您需要pdf文档,可以给我留言,我会将它发给你,在CSDN的下载中,您可能需要注册成为相关网站的会员,或者使用积分,如果您觉得麻烦,可以直接向我索取!点此获取!

posted on 2009-02-19 01:49 volnet 阅读(643) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


特殊功能