CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: C++ Tick timer

Threaded View

  1. #5
    Join Date
    Apr 2010
    Posts
    20

    Re: C++ Tick timer

    Since you are using Windows, you can use the performance counter.

    Code:
    #include <windows.h>
    #include <iostream>
    
    unsigned long long GetPerformanceTicks();
    unsigned long long GetPerformanceTicksInSecond();
    double GetTickSeconds(unsigned long long nTicks,unsigned long long nFreq);
    unsigned long long GetTickMilliseconds(unsigned long long nTicks,unsigned long long nFreq);
    unsigned long long GetTickMicroseconds(unsigned long long nTicks,unsigned long long nFreq);
    
    int main(int argc,char * argv)
    {
        unsigned long long nFreq = GetPerformanceTicksInSecond();
        unsigned long long nBefore = GetPerformanceTicks();
    
        CallSomeFunction();
    
        unsigned long long nAfter = GetPerformanceTicks();
    
        const unsigned long long nDiff = nAfter - nBefore;
    
        const unsigned long long nMicroseconds = GetTickMicroseconds(nTicks,nFreq);
    
        std::cout << "CallSomeFunction() took" << nMicroseconds << std::endl;
    
        return 0;
    }
    
    unsigned long long GetPerformanceTicks()
    {
        LARGE_INTEGER nValue;
    
        ::QueryPerformanceCounter(&nValue);
    
        return nValue.QuadPart;
    }
    
    unsigned long long GetPerformanceTicksInSecond()
    {
        LARGE_INTEGER nFreq;
    
        ::QueryPerformanceFrequency(&nFreq);
    
        return nFreq.QuadPart;
    }
    
    double GetTickSeconds(unsigned long long nTicks,unsigned long long nFreq)
    {
        return static_cast<double>(nTicks) / static_cast<double>(nFreq);
    }
    
    unsigned long long GetTickMilliseconds(unsigned long long nTicks,unsigned long long nFreq)
    {
        unsigned long long nTicksInMillisecond = nFreq / 1000;
    
        return nTicks / nTicksInMillisecond;
    }
    
    unsigned long long GetTickMicroseconds(unsigned long long nTicks,unsigned long long nFreq)
    {
        unsigned long long nTicksInMicrosecond = nFreq / 1000000;
    
        return nTicks / nTicksInMicrosecond;
    }
    Last edited by CppCoder2010; January 28th, 2011 at 03:48 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured