Skip to content

Instantly share code, notes, and snippets.

@davidjpfeiffer
Created December 6, 2017 16:49
Show Gist options
  • Save davidjpfeiffer/a61965cf2251b46eaa89b5ea483a85cc to your computer and use it in GitHub Desktop.
Save davidjpfeiffer/a61965cf2251b46eaa89b5ea483a85cc to your computer and use it in GitHub Desktop.
A comparison of execution times for a static method and a dynamic method in C++
#include <iostream>
#include <cstdlib>
#include <Windows.h>
#include <limits.h>
using namespace std;
class Base
{
public:
virtual int ExecuteDynamicMethod() = 0;
int ExecuteStaticMethod()
{
return rand() % INT_MAX;
}
};
class Derived: public Base
{
public:
int ExecuteDynamicMethod()
{
return rand() % INT_MAX;
}
};
// Windows
#ifdef _WIN32
#include <Windows.h>
double getWallTime(){
LARGE_INTEGER time,freq;
if (!QueryPerformanceFrequency(&freq)){
cout << "There was an error in the getWallTime method\n";
throw;
}
if (!QueryPerformanceCounter(&time)){
cout << "There was an error in the getWallTime method\n";
throw;
}
return (double)time.QuadPart / freq.QuadPart;
}
// Posix/Linux
#else
#include <time.h>
#include <sys/time.h>
double getWallTime(){
struct timeval time;
if (gettimeofday(&time,NULL)){
cout << "There was an error in the getWallTime method\n";
throw;
}
return (double)time.tv_sec + (double)time.tv_usec * .000001;
}
#endif
double getStaticExecutionTime(Base * base)
{
double start = getWallTime();
for(unsigned i = 0; i < 100000000; i++)
{
base->ExecuteStaticMethod();
}
return getWallTime() - start;
}
double getDynamicExecutionTime(Base * base)
{
double start = getWallTime();
for(unsigned i = 0; i < 100000000; i++)
{
base->ExecuteDynamicMethod();
}
return getWallTime() - start;
}
void printResults(double staticTime, double dynamicTime)
{
cout << "Time to execute static method: " << staticTime << " seconds.\n";
cout << "Time to execute dynamic method: " << dynamicTime << " seconds.\n";
cout << "The dynamic method took " << dynamicTime - staticTime << " seconds longer to execute.\n";
}
int main()
{
srand(getWallTime());
Base * base = new Derived();
double staticTime = getStaticExecutionTime(base);
double dynamicTime = getDynamicExecutionTime(base);
printResults(staticTime, dynamicTime);
return 0;
}
/*
------------
Results
------------
Time to execute static method: 1.51672 seconds.
Time to execute dynamic method: 1.56267 seconds.
The dynamic method took 0.045955 seconds longer to execute.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment