Last active
December 12, 2016 15:36
-
-
Save mkolod/db3ea1d932b95ce68ca8c40e5bffe854 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* Naive (conditional) and optimized (branchless) absolute value */ | |
#include <ctime> | |
#include <iostream> | |
#include <functional> | |
using namespace std; | |
int abs_naive(const int i) { | |
return i < 0 ? -i : i; | |
} | |
int abs_opt(const int i) { | |
int value = i; | |
int temp = i >> 31; | |
value ^= temp; | |
value += temp & 1; | |
return value; | |
} | |
double time_it(const long num_iter, const std::function<int(int)> f, const int num_to_eval = -101) { | |
volatile int result = 0; | |
clock_t begin1 = clock(); | |
for (long i = 0; i < num_iter; i++) { | |
result = f(num_to_eval); | |
} | |
clock_t end1 = clock(); | |
double elapsed_secs1 = double(end1 - begin1) / CLOCKS_PER_SEC; | |
return elapsed_secs1; | |
} | |
int main() { | |
const long numiter = 100000000; | |
cout << "\nTiming in seconds for " << numiter << " iterations" << endl << endl; | |
std::cout << "Naive: " << time_it(numiter, abs_naive) << "\n"; | |
std::cout << "Optimized: " << time_it(numiter, abs_opt) << "\n\n"; | |
std::cout << "abs_naive(-101) = " << abs_naive(-101) << "\n"; | |
std::cout << "abs_naive(101) = " << abs_naive(101) << "\n"; | |
std::cout << "abs_opt(-101) = " << abs_opt(-101) << "\n"; | |
std::cout << "abs_opt(101) = " << abs_opt(101) << "\n\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile with
Output: