Skip to content

Instantly share code, notes, and snippets.

@Gerold103
Last active September 29, 2023 16:11
Show Gist options
  • Save Gerold103/e7c06ee84b03c61a29b7fc1dff416e77 to your computer and use it in GitHub Desktop.
Save Gerold103/e7c06ee84b03c61a29b7fc1dff416e77 to your computer and use it in GitHub Desktop.
BenchFalseSharing
#include <atomic>
#include <ctime>
#include <iostream>
#include <thread>
static constexpr int workerCount = 1;
static constexpr uint64_t target = 400'000'000;
// Vary this value between 0 and 128 to see the difference.
static constexpr int paddingSize = 128;
struct object {
std::atomic_uint64_t input = 0;
char padding[paddingSize];
std::atomic_uint64_t output = 0;
};
static void inputF(object &obj, uint64_t target)
{
while (obj.input.fetch_add(1, std::memory_order_relaxed) < target)
continue;
}
static void outputF(object &obj, uint64_t target)
{
while (obj.output.fetch_add(1, std::memory_order_relaxed) < target)
continue;
}
int main()
{
object obj;
std::thread inputWorkers[workerCount];
std::thread outputWorkers[workerCount];
timespec t1;
clock_gettime(CLOCK_MONOTONIC, &t1);
for (std::thread &t : inputWorkers)
t = std::thread(inputF, std::ref(obj), target);
for (std::thread &t : outputWorkers)
t = std::thread(outputF, std::ref(obj), target);
for (std::thread &t : inputWorkers)
t.join();
for (std::thread &t : outputWorkers)
t.join();
timespec t2;
clock_gettime(CLOCK_MONOTONIC, &t2);
uint64_t usec = (t2.tv_sec * 1'000'000 + t2.tv_nsec / 1000) -
(t1.tv_sec * 1'000'000 + t1.tv_nsec / 1000);
std::cout << usec << " us" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment