Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python

C++


JAVA
PHP
SQL
Alice

TimingThings


TimingThings.cpp

// TimingThings.cpp
//
// Charles A. Cusack, 2008
//
// A simple program that demonstrates how you can time things in a C++
// program.
//
// This code should work on both UNIX and Windows, and mayve MACs.
//
// If you run this several times, you will see that the output is not 
// always the same.  This is because the method used is to get the time
// before and after the operation and subtract, so the total elapsed time
// is output.  This is not the same as the number of operations or the
// total cpu time used--it is wall-clock time.  Thus, it is affected by
// anything else running on the same computer.  This is where running
// multiple trials can help (although it does not fix the problem entirely). 
//
//
//
// There seem to be several ways to do timing with C++.  
// Here they are, with the positivs eand negatives:
//
// ftime       Seems to work, have resolution in milliseconds, and
//             works in UNIX and Windows.
//             I tested it using Visual C++ .NET and it seemed to work
//             just fine.  It also works fine on Solaris.
//             This is the method that is used below, since it is
//             cross-platform, and  seems to give pretty stable results.
//             I also am pretty sure this will work with C programs.
//
// hrtime      Is very high resolution, and seems to be pretty accurate.
//             hrtime_t is expressed in nanoseconds, which makes it
//             1,000,000 more times "accurate" than the other methods.
//             (Accurate is in quotes becase although the resolution is
//             higher, it might not be accurate down to the nanosecond.)
//             works on Solaris, and mayby other UNIX operating systems.
//             When I ran it with both this and the ftime method
//             they seemed to agree (except these times were in nanoseconds,
//             of course), which is a good sign.
//             Examples of using this method are included in comments.
//
// time_t      only gives resolution in seconds.  Useless for timing
//             operations unless they tak a long time.
//             This may be cross platform, but it still isn't accurate 
//             enough to use in most cases.
//
// clock_t     seems to have resolution in no more than milliseconds.
//             Also, gives very different answers than the others.
//             (e.g. ftime and hrtime both say 50 milliseconds, and
//             this one said 75 in one case--I tried several times 
//             with the same results).
//             I don't trust this method.  Not sure, but this may also
//             be a UNIX only one.
//             Examples of using this method are included in comments.
//
//-------------------------------------------------------------------------
// #include<sys/times.h> // Needed for hrtime_t
// #include<ctime> // Needed for clock_t
#include<sys/timeb.h> // Needed for ftime/timeb method.
#include <iostream>
using namespace std;
//-------------------------------------------------------------------------

int blah(int x);  // A sample method to test.
void timeOnce(int x);
void timeSeveralTrials(int x,int trials);

//-------------------------------------------------------------------------
int main (int argc,char* argv[]) {

    int a = 10000;
    int trials = 100;

    timeOnce(a);

    timeSeveralTrials(a,trials);

    return 0;
}
//-------------------------------------------------------------------------
// Run one trial of blah
void timeOnce(int x) {
    // Get the time before
    timeb start;
    ftime(&start);

    // Do whatever you want to time
    int answer = blah(x);   
    cout<<"Answer: "<<answer<<"\n";

    // Get the time after
    timeb end;
    ftime(&end);

    // The difference in time in seconds
    int ds = end.time - start.time;

    // The difference in time of the millisecond portion of the time.
    int dms = end.millitm - start.millitm;
    // The total time in milliseconds it took
    double avgTime=ds*1000 + dms;

    cout<<avgTime<<" milliseconds\n";

}

//-------------------------------------------------------------------------
// Run multiple trials of blah
void timeSeveralTrials(int x,int trials) {
    int answer=0;

    // Get time before using the "ftime" method
    timeb start;
    ftime(&start);

    // The alternative methods:
    // Get time before using the "clock" method
    // clock_t startTime=clock(); 
    // 
    // Get time before using the "hrtime" method
    //  hrtime_t startTime=gethrtime();

    for(int i=0;i<trials;i++) {
       answer = blah(x);
       // You MAY want to output the answer (or something else)
       // since compilers might optimize this call out since
       // calling it once has the same result as calling it 
       // multiple times.
       // If not here, you must use the variable somewhere or
       // the compiler will yell at you.
       cout<<"Answer: "<<answer<<"\n";
    }

    // Get time before using the "ftime" method
    timeb end;
    ftime(&end);

    // The alternative methods:
    // Get time after using the "clock" method
    // clock_t endTime=clock();
    //
    // Get time after using the "hrtime" method
    // hrtime_t endTime = gethrtime();

    // Get the elapsed time in milliseconds
    int ds = end.time - start.time;
    int dms = end.millitm - start.millitm;
    double avgTime=(ds*1000 + dms)*1.0/trials;

    // The alternative methods:
    // Get the elapsed time in milliseconds using the "clock" method.
    // You have to multiply by 1000 since the answer is in seconds.
    // double totalTime=1000*(endTime-startTime)*1.0/CLOCKS_PER_SEC;
    // double avgTime = totalTime/trials; 
    //
    // Get the elapsed time in nanoseconds using the "hrtime" method.
    // Notice that this is in nanoseconds (10^-9), while the others
    // are in milliseconds (10^-3).
    // double avgTimeHR = (endTime-startTime)*1.0/trials;
    
    // Output the results
    cout<<avgTime<<" milliseconds per trial for "<<trials<<" trials\n";

    // Output when using hrtime method.
    // cout<<avgTimeHR<<" nanoseconds per trial for "<<trials<<" trials (HR)\n";
}

//-------------------------------------------------------------------------
// Just a sample method.
//
int blah(int x) {
    int number = 0;
    for(int i=0;i<x;i++) {
	for(int j=0;j<i;j++)
        number += i-j;
    }
    return number;
}
//-------------------------------------------------------------------------