0

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

4

1 回答 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;

为了完整起见,我这样构建它(文件名 par.cpp):

make CXXFLAGS="-pthread -O3 -lrt" LDLIBS=-lrt -B par && ./par
于 2012-11-14T08:00:27.530 回答