我使用命令在 Ubuntu 12.04 中构建
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 个核心,但正常模式的持续时间更短。