我使用命令
在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个核心,但正常模式的持续时间较短。
答案 0 :(得分: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