- 论坛徽章:
- 2
|
我有下面一个这样的测试程序:
- #include<pthread.h>
- #include<stdlib.h>
- struct M{
- long a;
- long b;
- }obj;
- size_t count=2000000000;
- void* addx(void*args){
- long*pl=(long*)args;
- for(size_t i=0;i<count;++i)
- (*pl)*=i;
- return NULL;
- }
- int main(int argc,char*argv[]){
- pthread_t tid[2];
- pthread_create(&tid[0],NULL,addx,&obj.a);
- pthread_create(&tid[1],NULL,addx,&obj.b);
- pthread_join(tid[0],NULL);
- pthread_join(tid[1],NULL);
- return 0;
- }
复制代码
用clang来测试,注意已经加了-O2优化选项:
- clang++ test03_threads.cpp -o test03_threads -lpthread -O2 && time ./test03_threads
- real 0m3.626s
- user 0m6.595s
- sys 0m0.009s
复制代码
看起来挺慢的,我把全局obj改成*obj,运行时创建。我期待这个会更慢一点:
- #include<pthread.h>
- #include<stdlib.h>
- struct M{
- long a;
- long b;
- }*obj;
- size_t count=2000000000;
- void* addx(void*args){
- long*pl=(long*)args;
- for(size_t i=0;i<count;++i)
- (*pl)*=i;
- return NULL;
- }
- int main(int argc,char*argv[]){
- obj=new M;
- pthread_t tid[2];
- pthread_create(&tid[0],NULL,addx,&obj->a);
- pthread_create(&tid[1],NULL,addx,&obj->b);
- pthread_join(tid[0],NULL);
- pthread_join(tid[1],NULL);
- delete obj;
- return 0;
- }
复制代码
但是出乎我的意料,变快了:
- clang++ test03_threads_new.cpp -o test03_threads_new -lpthread -O2 && time ./test03_threads_new
- real 0m1.880s
- user 0m3.745s
- sys 0m0.007s
复制代码
而且快了差不多100%。我用linux+gcc测试了一下,一样的结果。
这到底是什么,什么原因造成了这么大的性能差异?
|
|