0

I build in Ubuntu 12.04 with command

g++ -pthread hello.cpp

But I run parallel mode always slows than normal . Here's my code

#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;
}

I run with 4 threads because my lap has 4 cores . I saw in System Monitor , I realize my lap used 4 cores concurrently in parrallel mode and only 1 core in normal mode but duration time of normal mode is shorter .

Toan Nguyen
  • 1,043
  • 3
  • 13
  • 24

1 Answers1

1

please see answer https://stackoverflow.com/a/2962914/1689451 for clarification of how clock works in multithreaded applications.

try it like this:

    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;

and for completeness, i built it like this (filname par.cpp):

make CXXFLAGS="-pthread -O3 -lrt" LDLIBS=-lrt -B par && ./par
Community
  • 1
  • 1
Rudolf Mühlbauer
  • 2,511
  • 16
  • 18