std::atomic<int>為了比較 和std::mutexprotected 之間的性能差異int,我有這個測驗程式:
#include <iostream>
#include <atomic>
#include <mutex>
#include <thread>
#include <chrono>
#include <limits>
using namespace std;
#ifndef INT_MAX
const int INT_MAX = numeric_limits<std::int32_t>::max();
const int INT_MIN = numeric_limits<std::int32_t>::min();
#endif
using std::chrono::steady_clock;
const size_t LOOP_COUNT = 12500000;
const size_t THREAD_COUNT = 8;
int intArray[2] = { 0, INT_MAX };
atomic<int> atomicArray[2];
void atomic_tf() {//3.19s
for (size_t i = 0; i < LOOP_COUNT; i) {
atomicArray[0] ;
atomicArray[1]--;
}
}
mutex m;
void mutex_tf() {//0.25s
m.lock();
for (size_t i = 0; i < LOOP_COUNT; i) {
intArray[0] ;
intArray[1]--;
}
m.unlock();
}
int main() {
{
atomicArray[0] = 0;
atomicArray[1] = INT_MAX;
thread tp[THREAD_COUNT];
steady_clock::time_point t1 = steady_clock::now();
for (size_t t = 0; t < THREAD_COUNT; t) {
tp[t] = thread(atomic_tf);
}
for (size_t t = 0; t < THREAD_COUNT; t) {
tp[t].join();
}
steady_clock::time_point t2 = steady_clock::now();
cout << (float)((t2 - t1).count()) / 1000000000 << endl;
}
{
thread tp[THREAD_COUNT];
steady_clock::time_point t1 = steady_clock::now();
for (size_t t = 0; t < THREAD_COUNT; t) {
tp[t] = thread(mutex_tf);
}
for (size_t t = 0; t < THREAD_COUNT; t) {
tp[t].join();
}
steady_clock::time_point t2 = steady_clock::now();
cout << (float)((t2 - t1).count()) / 1000000000 << endl;
}
return 0;
}
我在windows/linux上多次運行這個程式(用clang 14、g 12編譯),結果基本相同。
atomic_tf將需要 3 秒以上mutex_tf將需要 0.25 秒。
幾乎10倍的性能差異。
我的問題是,如果我的測驗程式是有效的,那么它是否表明使用原子變數比使用互斥鎖 普通變數要貴得多?
這種性能差異是怎么來的?謝謝!
uj5u.com熱心網友回復:
您的測驗并沒有真正比較mutex 與 atomic的性能:
您的互斥鎖版本將互斥鎖鎖定一次,然后進行
12500000迭代,而無需為執行緒同步機制支付任何額外費用。在您的原子版本
12500000中,您為每次遞增和每次遞減原子值(每次發生次數)支付原子同步的成本。
為了比較兩者,您需要在值的每次遞增或遞減時鎖定和解鎖互斥鎖。
就像是:
void mutex_tf()
{
for (size_t i = 0; i < LOOP_COUNT; i)
{
m.lock();
intArray[0] ;
m.unlock();
m.lock();
intArray[1]--;
m.unlock();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513363.html
上一篇:帶有模板模板引數的模板決議
