Created
December 6, 2017 16:49
-
-
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++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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