stringstream bad performance in multithread environment.

Post questions regarding programming in C/C++ in Linux/Unix.

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

stringstream bad performance in multithread environment.

Postby seacathello » Tue Jun 26, 2012 2:49 am

I use stl ostringstream in the multithreading environment.
I found that the execution time of each thread increased linearly as the thread number increased. But I did't find any synchronization code. I replace ostringsstream with snprintf and the preformance increase largely.

os: redhat 6.1 64bit
g++: g++4.4
cpu :4 core 2.0Ghz.

the code list as below:

Code: Select all
#include <iostream>
#include <sstream>
using namespace std;

void * func(void * t)
{
        int n = *((int *) t);
        pthread_t pid = pthread_self();
        timeval t1, t2;
        gettimeofday(&t1, 0);
        for(int i = 0; i < n; i++)
        {
                ostringstream os;
                /*
                   char buf[255];
                   int ret = snprintf(buf, 30, "%d", 2000000);
                   buf[ret] = 0;
                 */
        }
        gettimeofday(&t2, 0);
#define DIFF(a, b) ((b.tv_sec - a.tv_sec) + (b.tv_usec - a.tv_usec) / 1000000.0)
        std::cout << pid << ":" << DIFF(t1, t2) << std::endl;
#undef DIFF

        return NULL;
}

int main(int argc, char *argv[])
{
        int m, n =0;
        m = atoi(argv[1]);
        n = atoi(argv[2]);
        pthread_t tid[m];
        for(int i = 0; i < m; i++)
                pthread_create(&tid[i], NULL, func, &n);
        for(int i = 0; i < m; i++)
                pthread_join(tid[i], NULL);
        return 0;
seacathello
 
Posts: 1
Joined: Tue Jun 26, 2012 2:45 am

Return to Unix/Linux

Who is online

Users browsing this forum: No registered users and 1 guest