#include <time.h>
#include <atomic>
#include <mutex>
static std::atomic<bool> single_threaded(true);
int main(int argc, char *argv[])
{
(void)argv;
if (argc == 100001) { single_threaded = !single_threaded; /* to prevent compiler optimization later */ }
int n = argc == 100000 ? -1 : 10000000;
{
std::mutex mutex;
clock_t const begin = clock();
unsigned int total = 0;
for (int i = 0; i < n; ++i)
{
if (single_threaded)
{
total = ((total << 1) ^ i) + ((total >> 1) & i);
}
else
{
std::lock_guard<std::mutex> lock(mutex);
total = ((total << 1) ^ i) + ((total >> 1) & i);
}
}
clock_t const end = clock();
printf("Conditional: %u ms, total = %u\n", (unsigned int)((end - begin) * 1000U / CLOCKS_PER_SEC), total);
}
{
std::mutex mutex;
clock_t const begin = clock();
unsigned int total = 0;
for (int i = 0; i < n; ++i)
{
std::lock_guard<std::mutex> lock(mutex);
total = ((total << 1) ^ i) + ((total >> 1) & i);
}
clock_t const end = clock();
printf("Unconditional: %u ms, total = %u\n", (unsigned int)((end - begin) * 1000U / CLOCKS_PER_SEC), total);
}
}
I2luY2x1ZGUgPHRpbWUuaD4KCiNpbmNsdWRlIDxhdG9taWM+CiNpbmNsdWRlIDxtdXRleD4KCnN0YXRpYyBzdGQ6OmF0b21pYzxib29sPiBzaW5nbGVfdGhyZWFkZWQodHJ1ZSk7CgppbnQgbWFpbihpbnQgYXJnYywgY2hhciAqYXJndltdKQp7Cgkodm9pZClhcmd2OwoJaWYgKGFyZ2MgPT0gMTAwMDAxKSB7IHNpbmdsZV90aHJlYWRlZCA9ICFzaW5nbGVfdGhyZWFkZWQ7IC8qIHRvIHByZXZlbnQgY29tcGlsZXIgb3B0aW1pemF0aW9uIGxhdGVyICovIH0KCWludCBuID0gYXJnYyA9PSAxMDAwMDAgPyAtMSA6IDEwMDAwMDAwOwoJewoJCXN0ZDo6bXV0ZXggbXV0ZXg7CgkJY2xvY2tfdCBjb25zdCBiZWdpbiA9IGNsb2NrKCk7CgkJdW5zaWduZWQgaW50IHRvdGFsID0gMDsKCQlmb3IgKGlud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