2012-11-14 31 views
0

慢我建立在Ubuntu 12.04使用命令Pthread的程序始終運行較正常

g++ -pthread hello.cpp

但我並行運行模式總是慢比正常。這是我的代碼

#include <iostream> 
#include <pthread.h> 
#include <math.h> 

using namespace std; 

#define NUM_THREADS 4 
#define MAX_NUMBER 10000000 

void *doSomething(void *param) 
{ 
    int id = (int) param; 
    int sum = 0; 
    for (int i = 0; i < MAX_NUMBER; i++) 
    { 
     sum += sin(i) + cos(i) + tan(i);  // sum 
    } 
    return NULL; 
} 

void runNormal() 
{ 
      // run in normal mode with NUM_THREADS times. 
    for (int i = 0; i < NUM_THREADS; i++) 
    { 
     doSomething((void *) i); 
    } 
} 

void runParallel() 
{ 
    pthread_t threads[NUM_THREADS]; 
    pthread_attr_t attr; 
    pthread_attr_init(&attr); 
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); 

    int rc, i; 
    for (i = 0; i < NUM_THREADS; i++) 
    { 
     rc = pthread_create(&threads[i], &attr, doSomething, (void *) i); 
     if (rc) 
     { 
      cout << "ERROR : can't create thread #" << i; 
     } 
    } 

    pthread_attr_destroy(&attr); 
    void *status; 
    for (i = 0; i < NUM_THREADS; i++) 
    { 
     pthread_join(threads[i], &status); 
    } 
} 

int main() 
{ 
    int type; 
    cout << "Choose type of run (1 - normal, 2 - parallel) : "; 
    cin >> type; 
    clock_t init, final; 
    init = clock(); 
    if (type == 1) 
    { 
     runNormal(); 
    } 
    else if (type == 2) 
    { 
     runParallel(); 
    } 
    else 
    { 
     cout << "Your choice is wrong."; 
    } 
    final = clock(); 
    double duration = (double) (final - init)/CLOCKS_PER_SEC; 
    cout << "Duration : " << duration << " seconds." << endl; 

    pthread_exit(NULL); 
    return 0; 
} 

我跑4線程,因爲我的膝蓋有4個核心。我在系統監視器中看到,我意識到我的圈在並行模式下併發使用4個內核,在正常模式下只有1個內核,但正常模式的持續時間更短。

回答

1

請參閱回答https://stackoverflow.com/a/2962914/1689451以瞭解clock如何在多線程應用程序中工作。

嘗試這樣的:

struct timespec start, finish; 
    double elapsed; 
    clock_gettime(CLOCK_MONOTONIC, &start); 
    if (type == 1) 
    { 
     runNormal(); 
    } 
    else if (type == 2) 
    { 
     runParallel(); 
    } 
    else 
    { 
     cout << "Your choice is wrong."; 
    } 
    clock_gettime(CLOCK_MONOTONIC, &finish); 

    elapsed = (finish.tv_sec - start.tv_sec); 
    elapsed += (finish.tv_nsec - start.tv_nsec)/1000000000.0; 
    cout << " Duration : " << elapsed << " seconds." << endl; 

和完整性,我建立像這樣(FILNAME par.cpp):

make CXXFLAGS="-pthread -O3 -lrt" LDLIBS=-lrt -B par && ./par