Skip to content

Instantly share code, notes, and snippets.

@mkolod
Last active December 12, 2016 15:36
Show Gist options
  • Save mkolod/db3ea1d932b95ce68ca8c40e5bffe854 to your computer and use it in GitHub Desktop.
Save mkolod/db3ea1d932b95ce68ca8c40e5bffe854 to your computer and use it in GitHub Desktop.
/* 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";
}
@mkolod
Copy link
Author

mkolod commented Oct 5, 2016

Compile with

g++ abs.cpp -O3 --std=c++11 -o abs && ./abs

Output:

Timing in seconds for 100000000 iterations

Naive: 0.283806
Optimized: 0.23181

abs_naive(-101) = 101
abs_naive(101) = 101
abs_opt(-101) = 101
abs_opt(101) = 101

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment