I have a good program that shows the performance of two similar programs that use 2 threads to execute. The main difference is that a global variable is used, the other uses a βnewβ object, as shown below:
#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++ test03_threads.cpp -o test03_threads -lpthread -O2 && time ./test03_threads
real 0m3.626s
user 0m6.595s
sys 0m0.009s
This is pretty slow, then I modified obj for dynamic creation (I expected it to be even slower):
#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
This is surprisingly 100% faster than the previous one. I also tried g ++ on linux, same result. But how to explain it? I know that obj is a global variable, but * obj is a global variable, just dynamically created. What is the main difference?