Click here to Skip to main content
15,883,606 members
Articles / Desktop Programming / MFC

Timer class - Time how long your programs run for

Rate me:
Please Sign up or sign in to vote.
1.49/5 (12 votes)
20 Dec 2007CPOL1 min read 34.6K   403   17  
Time how long an application or a set of processes run for, to millisecond precision.
//
// timer.cpp : Defines the timer class. See header file for more information.
//
// Made by: Robert Roose
//          summatix
//

#include "timer.h"
#include <sstream>

// Constructors and destructors
//

timer::timer()
{
    running = false;
    startClock = 0;
    startTime = 0;
    accTime = 0;
    clockType = standard;
}

// Bool constuctor starts the timer immediately after creation of the object if the argument
// received is true.
//
timer::timer(const bool& start)
{
    running = false;
    startClock = 0;
    startTime = 0;
    accTime = 0;
    clockType = standard;

    //If the client has chosen to start the timer, then start the timer
    if (start)  {
        timer::start();
    }
}
//

//

// timer::start() starts the timer. If the timer is already running, nothing happens and the
// method returns. The timer automatically accumaltes the time if it has been started before.
//
void timer::start()
{
    // Return if the timer is already running
    if (running)
        return;

    // Set timer status to running and set the start time
    running = true;
    startClock = clock();
    startTime = time(0);
}
//

// timer::restart stops the current timer, and then resets the instance with the defualt values.
// If the timer has not started, the method returns without doing anything.
//
void timer::restart()
{
    if (!running)  { //If the timer has started
        // Set timer status to running, reset accumulated time, and set start time
        running = true;
        accTime = 0;
        startClock = clock();
        startTime = time(0);
    } else
        return;
}
//

// timer::stop stops (or pauses) the timer from running. If the timer has not started, the
// method returns having done nothing.
//
void timer::stop()
{
    // Compute accumulated running time and set timer status to not running
    if (running)  {
        accTime += elapsedTime();
        running = false;
    }
}
//

// timer::getNoOfSecs returns the number of seconds which the timer has been running for. This
// can be used both by the client, and as a helper method for the class.
//
double timer::getNoOfSecs() const
{
    if (!running)  {
        return accTime;
    } else  {
        return (elapsedTime() + accTime);
    }
}
//

// timer::setClockType( type )  sets the timer's clockType to the type specified by the client.
// Arguments allowed: standard, cpuClock, systemClock.
//
void timer::setClockType(const type& type)
{
    switch (type)  {
        case standard:
            clockType = standard;
        break;

        case cpuClock:
            clockType = cpuClock;
        break;

        case systemClock:
            clockType = systemClock;
        break;

        default:
        break;
    }
}
//

// timer::convertToString( int ) recieves an int value, converts the int to a string type, and
// then returns the string.
//
// This method uses the stringstream type defined in the sstream header to convert the int to a
// stringstream type, which can then be converted to a string type.
//
// This method does not interact with the class at all, so an object does not need to have been
// created before use of this method. This more closely relates to a function than a method.
//
std::string timer::convertToString(const int& valueToBeConverted)
{
    std::stringstream ssConverted;
    std::string stringConverted;

    //Store the int received from client into the stringstream variable
    ssConverted << valueToBeConverted;

    ssConverted >> stringConverted; //Store the converted int to the string variable

    return stringConverted;
}
//

// timer::convertToString( double ) recieves a double value, converts the double to a string type,
// and then returns the string.
//
// This method uses the stringstream type defined in the sstream header to convert the double to a
// stringstream type, which can then be converted to a string type.
//
// This method does not interact with the class at all, so an object does not need to have been
// created before use of this method. This more closely relates to a function than a method.
//
std::string timer::convertToString(const double& valueToBeConverted)
{
    std::stringstream ssConverted;
    std::string stringConverted;

    //Store the double received from client into the stringstream variable
    ssConverted << valueToBeConverted;

    ssConverted >> stringConverted; //Store the converted double to the string variable

    return stringConverted;
}
//

// Overloaded operator ostream '<<'. Allows timers to be printed to ostreams using the syntax
// 'os << t' for an ostream 'os' and a timer 't'.  For example, "cout << t" will print out the
// total amount of time the instance 't' has been running for. This will return in a format of
// "1hrs 1mins 1secs"
//
std::ostream& operator<<(std::ostream& os, timer& t)
{
    double timeElapsed;
    if (!t.running)  {
        timeElapsed = t.accTime;
    } else  {
        timeElapsed = t.elapsedTime() + t.accTime;
    }

    int hours = int(timeElapsed / 3600); //Determine the number of hours the timer has been running
                                         //for.
    timeElapsed -= hours * 3600;         //And subtract that amount from the remaining time.

    int minutes = int(timeElapsed / 60); //Determine the number of minutes the timer has been running
                                         //for.
    timeElapsed -= minutes * 60;         //And subtract that amount from the remaining time

    double seconds = timeElapsed;

    //Output the result, displaying only the necessary entities
    //
    if (hours == 0)  {
        if (minutes == 0)  {
            if (seconds == 0)  {
                os << "too quick to count";
            } else  {
                os << seconds << "secs";
            }
        } else  {
            os << minutes << "mins " << seconds << "secs";
        }
    } else  {
        os << hours << "hrs " << minutes << "mins " <<  seconds << "secs";
    }
    //

    return os;
}
//

// timer::elapsedTime() returns the total time that the timer has been running for. This method
// assumes that the client has already started the timer. This method is used as a helper method
// of the class.
//
double timer::elapsedTime() const
{
    //Find the difference in the current time and the time which the timer started in
    //the units of seconds
    time_t difference = time(0) - startTime;

    //Determine what the client has set clockType to, and return the appropriate value
    switch (clockType)  {
        case standard:
            //If the difference is less than an hour, return the cpu time
            if (difference < 3600)
                return (clock() - startClock) / (1.0 * CLOCKS_PER_SEC);

            //If the difference is larger than an hour, return the time difference
            else
                return (1.0 * difference);
        break;

        case cpuClock:
            return (1.0 * difference);
        break;

        case systemClock:
            return (clock() - startClock) / (1.0 * CLOCKS_PER_SEC);
        break;

        default:
            return 0.0;
        break;
    }
}
//

// Overlaoded operator for string types. Stores the running length of the timer into a string
// type variable.
//
timer::operator std::string() const
{
    double timeElapsed = getNoOfSecs();

    std::string result;

    int hours = int(timeElapsed / 3600); //Determine the number of hours the timer has been
                                         //running for.
    timeElapsed -= hours * 3600;         //And subtract that amount from the remaining time.

    int minutes = int(timeElapsed / 60); //Determine the number of minutes the timer has been
                                         //running for.
    timeElapsed -= minutes * 60;         //And subtract that amount from the remaining time

    double seconds = timeElapsed;

    //Determine the result, displaying only the necessary entities
    //
    if (hours == 0)  {
        if (minutes == 0)  {
            if (seconds == 0)  {
                result = "too quick to count";
            } else  {
                result = convertToString(seconds);
                result += "secs";
            }
        } else  {
            result = convertToString(minutes);
            result += "mins ";
            result += convertToString(seconds);
            result += "secs";
        }
    } else  {
        result = convertToString(hours);
        result += "hrs ";
        result = convertToString(minutes);
        result += "mins ";
        result += convertToString(seconds);
        result += "secs";
    }
    //

    return result;
}
//

// Overloaded operator int data type. Stores the number of seconds which the timer has been
// running for into an int data type variable.
//
timer::operator int() const
{
    return int(getNoOfSecs());
}
//

// Overloaded operator double data type. Stores the number of seconds which the timer has been
// running for into an double data type variable.
//
timer::operator double() const
{
    return (getNoOfSecs());
}
//

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions