Skip to content

Instantly share code, notes, and snippets.

@Mytherin
Created December 7, 2021 07:17
Show Gist options
  • Save Mytherin/4031d092797b1e8b84ba285745615926 to your computer and use it in GitHub Desktop.
Save Mytherin/4031d092797b1e8b84ba285745615926 to your computer and use it in GitHub Desktop.
#include <cstdint>
#include <chrono>
#include <iostream>
using namespace std;
int64_t naive_sum(int64_t x) {
int64_t sum = 0;
for(int64_t i = 0; i < x; i++) {
sum += i;
}
return sum;
}
int64_t clever_boy_sum(int64_t x) {
return x * (x + 1) / 2;
}
int main() {
int64_t xor_result = 7;
auto start =chrono::system_clock::now();
for(int i = 0; i < 100000000; i++) {
xor_result ^= naive_sum(100000000);
}
auto end = chrono::system_clock::now();
auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Naive Sum: " << elapsed.count() << "ms (" << xor_result << ")\n";
xor_result = 7;
start =chrono::system_clock::now();
for(int i = 0; i < 100000000; i++) {
xor_result ^= clever_boy_sum(100000000);
}
end = chrono::system_clock::now();
elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Clever Boy Sum: " << elapsed.count() << "ms (" << xor_result << ")\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment