2010-07-05

Yet another high-resolution timer in C++

Simple high-resolution timer in C++.

class StopWatch 
{
    private:

        LARGE_INTEGER start;
        LARGE_INTEGER stop;
        LARGE_INTEGER frequency;
        bool started;
        bool stopped;

    public:

        StopWatch(bool autoStart = true)
        {
            start.QuadPart = 0;
            stop.QuadPart = 0; 
            started = false;
            stopped = false;

            QueryPerformanceFrequency(&frequency);

            if (autoStart)
                StartTimer();
        }

        void StartTimer() 
        {
            if (started)
                AfxThrowNotSupportedException();

            started = true;
            stopped = false;

            QueryPerformanceCounter(&start);
        }

        void StopTimer(bool traceResult = true) 
        {
            QueryPerformanceCounter(&stop);

            if (!started)
                AfxThrowNotSupportedException();

            started = false;
            stopped = true;

            if (traceResult)
                AfxMessageBox(Helpers::StringFormat(L"Time [ms]: %d\n", 
                              GetElapsedTime()));
        }

        int GetElapsedTime() 
        {
            if (started)
                AfxThrowNotSupportedException();
            if (!stopped)
                AfxThrowNotSupportedException();

            return (int)((stop.QuadPart - start.QuadPart) * 1000 / 
                       frequency.QuadPart);
        }
};

Brak komentarzy:

Prześlij komentarz