Listing 2. C++ Benchmark Source Code

#include
#include
#include

const int NOBJECTS = 500000;

class PerfTest
{
public:
     PerfTest ();
     void addAmount (int val);
     int getAmount ();
private:
     int amount;
};

PerfTest::PerfTest ()
{
     amount = 0;
}

void PerfTest::addAmount (int val)
{
     amount += val;
}

int PerfTest::getAmount ()
{
     return amount;
}

void reportResult (struct timeval* tstart, struct timeval* tend);

/*
 *  C++ version of the test driver.
 *  Creates half a million simple account objects, adds an amount
 *  to each one, and then adds up the amounts in all accounts.
 *  Reports elapsed time in milliseconds and number of objects
 *  processed per millisecond.
 */
void main (int argc, char** argv)
{
     PerfTest* ptarr[NOBJECTS];
     struct timeval tval_start;
     struct timeval tval_end;
     struct timezone tzone;
     int sum = 0;
     int i = 0;

     gettimeofday (&tval_start, &tzone);

     for (i = 0; i < NOBJECTS; i++)
             ptarr[i] = new PerfTest;

     for (i = 0; i < NOBJECTS; i++)
             ptarr[i]->addAmount(i);

     for (i = 0; i < NOBJECTS; i++)
             sum += ptarr[i]->getAmount();

     gettimeofday (&tval_end, &tzone);

     reportResult (&tval_start, &tval_end);
}

/*
 *  Helper function to report results.
 */
void reportResult (struct timeval* tstart, struct timeval* tend)
{
     int start_ms = (tstart->tv_sec * 1000) +
     (tstart->tv_usec / 1000);
     int end_ms = (tend->tv_sec * 1000) +
     (tend->tv_usec / 1000);

     cout << "Elapsed time in milliseconds for "
     << NOBJECTS << " objects:  " <<
     (end_ms - start_ms) << "\n";
     cout << "Objects per millisecond:  "  <<
     (NOBJECTS / (end_ms - start_ms)) << "\n";
}