Created
March 14, 2015 18:51
-
-
Save Rhomboid/ce3e03b755ce2cacd592 to your computer and use it in GitHub Desktop.
The stupidity of using XOR to swap integers
This file contains 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
#include <iostream> | |
#include <vector> | |
#include <random> | |
#include <iterator> | |
#include <algorithm> | |
#include <functional> | |
#include <chrono> | |
using test_type = unsigned; | |
void stupid_swap(test_type &a, test_type &b) | |
{ | |
a ^= b; | |
b ^= a; | |
a ^= b; | |
} | |
double timeit(std::function<void(void)> func, int rep_count = 25) | |
{ | |
std::vector<double> times; | |
for(int i = 0; i < rep_count; i++) { | |
auto start = std::chrono::steady_clock::now(); | |
func(); | |
auto end = std::chrono::steady_clock::now(); | |
times.push_back(std::chrono::duration<double, std::chrono::microseconds::period>(end - start).count()); | |
} | |
return *min_element(begin(times), end(times)); | |
} | |
int main() | |
{ | |
const size_t num_elem = 10000000; | |
std::mt19937 rnd(0xdeadbeefU); | |
std::uniform_int_distribution<test_type> dist; | |
std::vector<test_type> data1, data2; | |
std::generate_n(back_inserter(data1), num_elem, [&]() { return dist(rnd); }); | |
std::generate_n(back_inserter(data2), num_elem, [&]() { return dist(rnd); }); | |
std::cout << "stupid_swap: " << timeit([&]() { | |
for(size_t i = 0; i < data1.size(); i++) { | |
stupid_swap(data1[i], data2[i]); | |
} | |
}) << "us\n"; | |
std::cout << "std::swap: " << timeit([&]() { | |
std::swap_ranges(begin(data1), end(data1), begin(data2)); | |
}) << "us\n"; | |
} |
This file contains 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
$ g++ -Wall -Wextra -pedantic -std=c++1y -O2 swaptest.cpp -o swaptest && ./swaptest | |
stupid_swap: 15855.7us | |
std::swap: 8926.66us |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment