C++ ------ 互斥锁、原子操作的性能测试
2017-11-16 10:51
1196 查看
atomic原子操作:是在新标准C++11,引入了原子操作的概念,并通过这个新的头文件提供了多种原子操作数据类型,例如,atomic_bool,atomic_int等等
测试程序
#include <iostream> #include <thread> #include <mutex> #include <atomic> #include <time.h> #define TEST_DATA_LENGTH 100000 //每个线程操作次数 #define THREAD_NUM 10 //线程个数 using namespace std;//引入std命名空间 mutex m;//声明互斥锁m long n_total = 0; long m_total = 0; atomic<long> a_total = 0;//原子量的初始化 //在不采用互斥锁和原子类的情况下 void test_f_normal() { for(int i = 0; i < TEST_DATA_LENGTH; i++) { n_total += 1; } } //使用mutex互斥锁 void test_f_mutex() { for(int i = 0; i < TEST_DATA_LENGTH; i++) { m.lock(); m_total += 1; m.unlock(); } } //使用原子操作 void test_f_atomic() { for(int i = 0; i < TEST_DATA_LENGTH; i++) { a_total += 1; } } void main() { thread ts[THREAD_NUM]; //normal mode ,result is error clock_t start = clock(); for(int i = 0; i < THREAD_NUM; i++) { ts[i] = thread(&test_f_normal); } for(int i = 0; i < THREAD_NUM; i++) { ts[i].join(); } clock_t end = clock(); cout << "total: " << n_total << endl; cout << "test_f_normal: " << end - start << endl; //use mutex , clock_t mstart = clock(); for(int i = 0; i < THREAD_NUM; i++) { ts[i] = thread(&test_f_mutex); } for(int i = 0; i < THREAD_NUM; i++) { ts[i].join(); } clock_t mend = clock(); cout << "total: " << m_total << endl; cout << "test_f_mutex: " << mend - mstart << endl; //use atomic clock_t astart = clock(); for(int i = 0; i < THREAD_NUM; i++) { ts[i] = thread(&test_f_atomic); } for(int i = 0; i < THREAD_NUM; i++) { ts[i].join(); } clock_t aend = clock(); cout << "total: " << a_total << endl; cout << "test_f_atomic: " << aend - astart << endl; system("pause"); return; }
测试结果
total: 601409 test_f_normal: 29 total: 1000000 test_f_mutex: 11274 total: 1000000 test_f_atomic: 35
总结
由上面的测试结果可以看得出来1.在不使用互斥锁和原子量的时候,多线程的操作会使结果是错误的.
2.原子操作的实现跟普通数据类型类似,但是它能够在保证结果正确的前提下,提供比mutex等锁机制更好的性能
提示:开发过程中,对于多线程的情况下,单个基础数据类型的数据共享安全,尽量使用原子操作代替锁机制. 当需要对代码块进行数据安全保护的时候,就需要选择使用锁机制或者自旋锁了。
相关文章推荐
- C++小品:榨干性能:C++11中的原子操作(atomic operation)
- C++小品:榨干性能:C++11中的原子操作(atomic operation) - [C++11 FAQ]
- C++原子操作实现互斥
- c++多个线程操作与互斥
- linux环境下 C++性能测试工具 gprof + kprof + gprof2dot
- OpenMP创建线程中的锁及原子操作性能比较
- 单链表的创建、打印、测试长度(基本操作)-C++
- 性能测试工具操作数据库(四)-Jmeter与Oracle
- OpenMP创建线程中的锁及原子操作性能比较
- 用c++封装一个Hash Table,并与STL map 进行操作性能上的比较
- linux环境下 C++ 性能测试工具 gprof 和 gprof2dot
- 【ThinkingInJava】55、对set中的操作测试性能比较
- 性能测试之字符串比较; C、C++和JAVA
- arm驱动程序——按键程序6_互斥1—原子操作(韦东山的视频总结及针对linux-2.6.30)
- Iperf 网络性能测试工具(操作备忘)
- 无锁编程[1]__关于CAS等原子操作,用CAS实现互斥锁
- OpenMP: 创建线程中的锁及原子操作性能比较
- C++实现链表的进本操作及测试用例
- 用c++做性能测试
- 接口性能测试(Jmeter)操作总结