Students often ask how they can test their algorithms for speed. I'll present you a simple, platform independent class to measure speeds. A function
main() is included to demonstrate its usage.
Question: After testing the three differenct loop-functions, why would anyone prefer a certain version?
stopwatch.h
Code:
#ifndef STOPWATCH_H
#define STOPWATCH_H
#include <ctime>
inline static double seconds()
{
const double secs_per_tick = 1.0 / std::CLOCKS_PER_SEC;
return ( (double) std::clock() ) * secs_per_tick;
}
class Stopwatch
{
private:
bool running_;
double start_time_;
double total_;
public:
inline Stopwatch();
inline void start();
inline double stop();
inline double read();
inline void resume();
inline int running();
};
inline Stopwatch::Stopwatch() :
running_(0), start_time_(0.0), total_(0.0)
{}
void Stopwatch::start()
{
running_ = true;
total_ = 0.0;
start_time_ = seconds();
}
double Stopwatch::stop()
{
if (running_)
{
total_ += (seconds() - start_time_);
running_ = 0;
}
return total_;
}
inline void Stopwatch::resume()
{
if (!running_)
{
start_time_ = seconds();
running_ = 1;
}
}
inline double Stopwatch::read()
{
if (running_)
{
stop();
resume();
}
return total_;
}
#endif //STOPWATCH_H
main.cpp
Code:
#include "stopwatch.h"
#include <iostream>
using namespace std;
unsigned dTestArray[200000000];
void do_loop()
{
unsigned i = 0;
do
{
dTestArray[i] = i;
++i;
} while(i < 200000000);
}
void while_loop()
{
unsigned i = 0;
while(i < 200000000)
{
dTestArray[i] = i;
++i;
}
}
void for_loop()
{
for(unsigned i = 0; i < 200000000; ++i)
{
dTestArray[i] = i;
}
}
int main()
{
Stopwatch W;
W.start();
for(unsigned i = 0; i < 20; ++i)
{
//Change the loop versions here to compare the loop speeds.
for_loop();
}
W.stop();
std::cout<<W.read()<<std::endl;
std::cin.get();
return 0;
}