Performance Comparison Between mutex and atomic in linux: mutexatomic
One is to use boost: atomic; one is to directly lock; the code is very simple:
# Include <boost/atomic. hpp> # include <iostream> # include <stdlib. h> # include <boost/thread/mutex. hpp> # include <pthread. h> # include <stdio. h> # include <sys/time. h> # include <time. h> static int loop_num = 10000; boost: atomic <int> a (0); static boost: mutex CTX _; static void * test_atomic (void * agr) {int num = * (int *) agr; struct timeval t_start, t_end; long cost_time = 0; gettimeofday (& t_start, NULL); long start = (long) t_start. TV _sec) * 1000 + (long) t_start. TV _usec/1000; while (num --) {++ a;} gettimeofday (& t_end, NULL); long end = (long) t_end. TV _sec) * 1000 + (long) t_end. TV _usec/1000; cost_time = end-start; std: cout <"loopnum: "<loop_num <" test_atomic cost "<cost_time <" ms \ n "; return NULL;} static int B = 0; static void * test_lock (void * agr) {int num = * (int *) agr; struct timeval t_start, t_end; long cost_time = 0; gettimeofday (& t_start, NULL); long start = (long) t_start. TV _sec) * 1000 + (long) t_start. TV _usec/1000; while (num --) {boost: mutex: scoped_lock lock (CTX _); + + B ;}} gettimeofday (& t_end, NULL); long end = (long) t_end. TV _sec) * 1000 + (long) t_end. TV _usec/1000; cost_time = end-start; std :: cout <"loopnum:" <loop_num <"test_lock cost" <cost_time <"ms \ n"; return NULL;} int main (int agrc, char ** argv) {if (agrc <2) {std: cout <"please input num:" <std: endl; return 0;} pthread_t main_tid; int num1 = atoi (char *) argv [1]); int num2 = atoi (char *) argv [2]); if (num1 = 0) {pthread_create (& main_tid, NULL, & test_atomic, & num2); // create a thread pthread_join (main_tid, NULL);} else {pthread_create (& main_tid, NULL, & test_lock, & num2); // create thread pthread_join (main_tid, NULL );}}
The test results are as follows:
Allen @ allen-ThinkPad-Edge-E431 :~ /Code $./test 0 1000
Loopnum: 10000 test_atomic cost 0 MS
Allen @ allen-ThinkPad-Edge-E431 :~ /Code $./test 1 1000
Loopnum: Drawing test_lock cost 0 MS
Allen @ allen-ThinkPad-Edge-E431 :~ /Code $./test 1 100000
Loopnum: Drawing test_lock cost 9 MS
Allen @ allen-ThinkPad-Edge-E431 :~ /Code $./test 0 100000
Loopnum: 10000 test_atomic cost 2 MS
As the number of loops increases, the gap increases. It is related to the implementation of the two. One is the blocking of the critical section, the other is the compare change technology, or even the internal implementation uses the assembly.
The result in my notebook is like this, which also illustrates the problem.