C ++ using global variable shows 100% slower than pointer when using pthread?

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;//difference 1
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;//difference 2
    pthread_t tid[2];
    pthread_create(&tid[0],NULL,addx,&obj->a);//difference 3
    pthread_create(&tid[1],NULL,addx,&obj->b);//difference 4
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    delete obj;//difference 5
    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?

+6
1

, - , .

, ?

- count! , size_t long, ( pl count). count int, - ( const size_t).

, count .

count obj . , , . obj.a obj.b count. , CPU count.

obj, count, . count.

+1

Source: https://habr.com/ru/post/1016695/


All Articles