difftime()

Declaration

double difftime(time_t qEndTime, time_t qStartTime);

Description:

This function returns the difference of the two argument times (qEndTime – qStartTime) in seconds. This is useful for calculating the elapsed time for a section of code.

Example

#include <iostream>
#include <ctime>

int main() {
    using namespace std;

    time_t qStartTime;
    time_t qEndTime;

    const unsigned int kuiNumberCount = 80000000;
    const unsigned int kuiModulus = 6;

    // Time the random number generator
    time(&qStartTime);
    for (unsigned int uiIndex = 0; uiIndex < kuiNumberCount; ++uiIndex) {
        unsigned int uiInteger = rand();
        unsigned int uiRand = (uiInteger % kuiModulus);
    }
    time(&qEndTime);

    double dElapsedSecs = difftime(qEndTime, qStartTime);
    cout << "Generating " << kuiNumberCount
        << " random numbers between 0 and "
        << (kuiModulus - 1) << " takes "
        << dElapsedSecs << " seconds." << endl;

    return 0;
}

Output:

difftime() Output