Listing 4: test_mt.cc — Test program for testing string performance in multithreaded programs

#include "xstr.h"
#include <string>
#include <thread.h>
#include <pthread.h>

int NUM_THREADS=5;
int NUM_ITERS=100000;
int secs[100];

void* test01(void* id) {
    clock_t t0 = clock();
    for (int i=1;i<NUM_ITERS;++i) {
        STRINGCLASS str1("Now this is a test...");
        STRINGCLASS str2("Now this is a test...");
        STRINGCLASS str3("Now this is a test...");
...etc...
        STRINGCLASS str10("Now this is a test...");
    }
    clock_t t1 = clock();
    secs[(int)id] = t1-t0;
}

int main(int argc, char *argv[]) {
    thr_setconcurrency(100);
    if (argc>=2) NUM_ITERS = atol(argv[1]);
    if (argc>=3) NUM_THREADS = atol(argv[2]);

    cout << "Creating  " << NUM_THREADS << " threads...\n";
    pthread_t tids[100];
    clock_t t0 = clock();
    for (int i=0;i<NUM_THREADS;++i) {
        pthread_create(&tids[i], NULL, test01, (void*)i);
    }
    for (int i=0;i<NUM_THREADS;++i) {
        void *v;
        pthread_join(tids[i],&v);
    }
    clock_t t1 = clock();
    double wall_time = (1000 * (double)(t1-t0))/CLOCKS_PER_SEC;
    cout << "Elapsed time for " << NUM_THREADS << 
            " threads @ " << NUM_ITERS <<
            " iters: " << wall_time << " msec\n";
}
— End of Listing —