- #include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- #include <pthread.h>
- #include <time.h>
- int main() {
- int x;
- time_t tm1, tm2;
- double timeDiff;
- const int MaxCount = 1000000000;
- x = 0;
- time(&tm1);
- for (int i = 0; i < 0x7FFFFFFF; i++)
- {
- x++;
- if (x > MaxCount) //0x10000000
- break;
- }
- time(&tm2);
- timeDiff = difftime(tm2, tm1);
- printf("Without Locker, timespand = %f\\n", timeDiff);
- pthread_mutex_t mutex;
- pthread_mutex_init(&mutex, NULL);
- x = 0;
- time(&tm1);
- for (int i = 0; i < 0x7FFFFFFF; i++)
- {
- pthread_mutex_lock(&mutex);
- x++;
- if (x > MaxCount) //0x10000000
- break;
- pthread_mutex_unlock(&mutex);
- }
- time(&tm2);
- timeDiff = difftime(tm2, tm1);
- printf("Using Locker, timespand = %f\\n", timeDiff);
- pthread_mutex_destroy(&mutex);
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/2711201411092.html
来源: http://www.codesnippet.cn/detail/2711201411092.html