I wrote the following code to test which is faster: performing a multiplication and division many times, or accessing the results in a vector via iterators(perform the calculations ahead of time), or hard coding the results of those calculations into the program. I actually expected storing the results in the vector to be faster than performing the calculations, but on my system I get the following relation for the times to complete each corresponding function:
Hard Coded Values < 5 * (On the fly calculations) < 50 * ( Vector Stored Values)
So my question is this: Am I stuck making these same calcuations over and over again (or hard coding their results), or is there a faster way to do it?
Note: My timer is for Windows, but I think the rest of the code is OS agnostic.
#include <windows.h>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
template <class Function>
__int64 time_call(Function&& f)
{
__int64 begin = GetTickCount();
f();
return GetTickCount() - begin;
}
int numberOfReps(100000000);
int dotFrequency(25000000);
class PreCalcObj
{
public:
PreCalcObj()
{
for (double i = 1; i < 4; ++i)
{
for (double j = 1; j < 4; ++j)
{
TiTjsumT2.push_back(i * j / 4597);
}
}
}
vector<double> TiTjsumT2;
};
double CalcAll()
{
double valReturn;
for (int iCount = 0; iCount < numberOfReps; ++iCount)
{
double bVal(33.23);
if (iCount % dotFrequency== 0)
{
cout << ".";
}
for (double i = 1; i < 4; ++i)
{
for (double j = 1; j < 4; ++j)
{
valReturn = bVal * i * j / 4597;
}
}
}
cout << valReturn << endl;
return valReturn;
}
double UsePreCalced(const PreCalcObj& mObj)
{
double valReturn;
double bVal(33.23);
for (int iCount = 0; iCount < numberOfReps; ++iCount)
{
if (iCount % dotFrequency== 0)
{
cout << ".";
}
for (auto it = mObj.TiTjsumT2.begin(); it != mObj.TiTjsumT2.end(); ++it)
{
valReturn = bVal * *it;
}
}
cout << valReturn << endl;
return valReturn;
}
double CalcHardCodedVAls()
{
double valReturn;
double bVal(33.23);
for (int iCount = 0; iCount < numberOfReps; ++iCount)
{
if (iCount % dotFrequency== 0)
{
cout << ".";
}
valReturn = bVal * .000217533178; // = bVal * 1*1 / 4597
valReturn = bVal * .000435066356; // = bVal * 2*1 / 4597
valReturn = bVal * .0006525995214; // = bVal * 3*1 / 4597
valReturn = bVal * .000435066356; // = bVal * 1*2 / 4597
valReturn = bVal * .0008701326952; // = bVal * 2*2 / 4597
valReturn = bVal * .00130519904; // = bVal * 3*2 / 4597
valReturn = bVal * .0006525995214; // = bVal * 1*3 / 4597
valReturn = bVal * .00130519904; // = bVal * 2*3 / 4597
valReturn = bVal * .00195779856; // = bVal * 3*3 / 4597
}
cout << valReturn << endl;
return valReturn;
}
int main(int argc, char* argv[])
{
PreCalcObj preCalced;
cout << "PreCalced values time: " << time_call([&] {UsePreCalced(preCalced);}) << endl;
cout << "All Calculated time: " << time_call([&] {CalcAll();}) << endl;
cout << "Hard Coded time: " << time_call([&] {CalcHardCodedVAls();}) << endl;
cin.get();
return 0;
}