Microsecond Benchmark
2008-11-02 16:55:19
Category: cpp:math
Description: Benchmark class with microsecond precision.
Author: detour
Viewed: 215
Rating: (2 votes)


/* benchmark.cpp by detour@metalshell.com
 *
 * benchmark class with microsecond precision.
 *
 */
 
#include <iostream>
#include <sys/time.h>
 
class benchmark {
  private:
    double _start;
 
  public:
    void start_bench();
    double end_bench();
};
 
void benchmark::start_bench() {
  struct timeval tv;
  gettimeofday(&tv, NULL);
 
  _start = (double)tv.tv_sec + ((double)tv.tv_usec / 1000000.0);
}
 
double benchmark::end_bench() {
  struct timeval tv;
  gettimeofday(&tv, NULL);
 
  return (((double)tv.tv_sec + ((double)tv.tv_usec / 1000000.0)) - _start);
}
 
int main() {
  benchmark n;
 
  std::cout.precision(10);
 
  n.start_bench();
  for(int x = 0; x < 10000; x++);
  std::cout << std::fixed << "Count to 10,000: " << n.end_bench() << std::endl;
 
  n.start_bench();
  for(int x = 0; x < 100000000; x++);
  std::cout << std::fixed << "Count to 100,000,000: " << n.end_bench() << std::endl;
 
  n.start_bench();
  for(unsigned long int x = 0; x < 1000000000ULL; x++);
  std::cout << std::fixed << "Count to 1,000,000,000: " << n.end_bench() << std::endl;
}