some benchmarking
I created a formula to add all the numbers between to numbers (1-100, 1+2+3...+99+100) and compared it to a for loop which is probably much more common, and easier to think of.
I don't see anything that might cause the comparison unfair, but if there is, can you find it?
I know this is too unrealistic when it comes to average programs, but just did it for benchmarking. What it does is
it will add all numbers between 1 and 10,000,000, for 10,000 times, and records the time required to execute it.
yes, my formula is correct and works, so yeah.
using my algorithm, it took around 3.2 seconds, while on the other hand, the for loop total got raped

Output:
i made them __int64s so they could work with huge numbers
I don't see anything that might cause the comparison unfair, but if there is, can you find it?
I know this is too unrealistic when it comes to average programs, but just did it for benchmarking. What it does is
it will add all numbers between 1 and 10,000,000, for 10,000 times, and records the time required to execute it.
yes, my formula is correct and works, so yeah.
using my algorithm, it took around 3.2 seconds, while on the other hand, the for loop total got raped

Output:
i made them __int64s so they could work with huge numbers
Code:
#include <iostream>
#include <time.h>
__int64 test(__int64 start, __int64 end)
{
__int64 total = 0;
if((end - start) % 2 == 0)
{
total = ((start+end)*((end-start)/2)) + (end/2) + 1;
}
else
{
total = (end + start) * (end/2);
}
return total;
}
__int64 test2(__int64 start, __int64 end)
{
__int64 total = 0;
for(__int64 i = 1; i <= end; i++)
{
total += i;
}
return total;
}
int main()
{
int sum = 0;
clock_t start, end,start2,end2;
start = clock();
for(int i = 0; i < 10000; i++)
{
std::cout << test(1,10000000) << '\n';
}
end = clock();
double time1 = (double)(end-start)/CLOCKS_PER_SEC;
std::cout << "Time required: " << time1 << " seconds.\n";
std::cout << "For the for loop function. Press enter. . . \n";
std::cin.get();
start2 = clock();
for(int i = 0; i < 10000; i++)
{
std::cout << test2(1,10000000) << '\n';
}
end2 = clock();
double time2 = (double)(end2-start2)/CLOCKS_PER_SEC;
std::cout << "Time required: " << time2 << " seconds.\n";
std::cout << "Formula executed " << time2 - time1 << " seconds faster than traditional for loop solution\n";
return 0;
}




