Files
multithread_experiments/experiments/mutex_multithread.cpp

71 lines
2.0 KiB
C++

#include <pimutex.h>
#include <piconditionlock.h>
#include <atomic>
#include <future>
#include <picout.h>
#include <vector>
float check_performance(std::function<long(long&)> test_function) {
long k = 0;
std::vector<std::future<float>> perThreadPerformance;
for (int j = 0; j < 6; ++j) {
auto future = std::async(std::launch::async, [=, &k](){
auto start = std::chrono::high_resolution_clock::now();
while (test_function(k) < 1000 * 1000) { }
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000.f;
});
perThreadPerformance.push_back(std::move(future));
}
float res = 0;
for (int j = 0; j < perThreadPerformance.size(); ++j) {
res += perThreadPerformance[j].get();
}
return res / perThreadPerformance.size();
}
int main() {
PIMutex piMutex;
auto piMutexPerformance = check_performance([&piMutex](long& k){
piMutex.lock();
int i = 0; while (i < 1000) { i++; }
long res = ++k;
piMutex.unlock();
return res;
});
piCout << "piMutex:" << piMutexPerformance << "ms";
PIConditionLock piConditionLock;
auto piConditionLockPerformance = check_performance([&piConditionLock](long& k){
piConditionLock.lock();
int i = 0; while (i < 1000) { i++; }
long res = ++k;
piConditionLock.unlock();
return res;
});
piCout << "piConditionLock:" << piConditionLockPerformance << "ms";
std::mutex stdMutex;
auto stdMutexPerformance = check_performance([&stdMutex](long& k){
stdMutex.lock();
int i = 0; while (i < 1000) { i++; }
long res = ++k;
stdMutex.unlock();
return res;
});
piCout << "stdMutex:" << stdMutexPerformance << "ms";
std::atomic_flag stdAtomic = ATOMIC_FLAG_INIT;
auto stdAtomicPerformance = check_performance([&stdAtomic](long& k){
while(stdAtomic.test_and_set(std::memory_order_acquire)) {
std::this_thread::yield();
}
int i = 0; while (i < 1000) { i++; }
long res = ++k;
stdAtomic.clear(std::memory_order_release);
return res;
});
piCout << "stdAtomic:" << stdAtomicPerformance << "ms";
}