Skip to content

Instantly share code, notes, and snippets.

@flandr
Last active August 29, 2015 14:20
Show Gist options
  • Save flandr/e5413b65559e9f066080 to your computer and use it in GitHub Desktop.
Save flandr/e5413b65559e9f066080 to your computer and use it in GitHub Desktop.
Should you care about an extra indirection when updating atomics?
#include <stdio.h>
#include <stdlib.h>
#include <atomic>
#include <chrono>
std::chrono::milliseconds direct(int iters) {
auto start = std::chrono::system_clock::now();
auto val = new std::atomic<int>[1];
for (int i = 0; i < iters; ++ i) {
val[0].fetch_add(1);
}
delete [] val;
auto end = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
}
std::chrono::milliseconds indirect(int iters) {
auto start = std::chrono::system_clock::now();
auto val = new std::atomic<int>*[1];
val[0] = new std::atomic<int>;
for (int i = 0; i < iters; ++ i) {
val[0]->fetch_add(1);
}
delete val[0];
delete [] val;
auto end = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <iterations>\n", argv[0]);
exit(1);
}
int iters = atoi(argv[1]);
auto dir = direct(iters);
auto ind = indirect(iters);
printf("%d iters: %lld direct, %lld indirect\n", iters, dir.count(), ind.count());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment