rand_test

testing how rand behaves within main thread and separate thread. On some systems it takes double the time if it's in separate thread.
mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.6 kB
19
Indexable
Never
/**
 * testing how rand behaves within main thread and separate thread.
 * On some systems it takes double the time if it's in separate thread.
 * compile with:
 *   g++ -std=c++11 test.cpp  -o test -lpthread
 * run:
 * time ./test <1-4>
 */

#include <cstdio>
#include <stdexcept>
#include <thread>
#include <future>
#include <malloc.h>
#include <time.h>

#define TEST_ITERATIONS 300*1000*1000

void *testNN(void *dummy) {
  volatile double x;
  for (int i = 0; i < TEST_ITERATIONS; ++i) {
    x = rand();
    x *= rand();
  }
  return nullptr;
}

int main(int argc, char *argv[]){
    time_t start = time(nullptr);

    { // for future to join thread

      int testVariant = 1;
      if(argc > 1){
        int i = atoi(argv[1]);
        if(i<1 || i>4){
          printf("please, enter value between 1 and 4\n");
        } else {
          testVariant = i;
        }
      }else{
        printf("running test No %d by default\n", testVariant);
      }
      std::future<void *> f[12];

      switch(testVariant){
        case 1:
          printf("main thread test\n");
          testNN(nullptr); // 12s
          break;
        case 2:
          printf("pthreads test\n");
          pthread_t thread_id;
          pthread_create(&thread_id, NULL, testNN, nullptr);
          pthread_join(thread_id, NULL); //27s
          break;
        case 3:
          printf("std::async test\n");
          f[0] = std::async(std::launch::async, testNN, nullptr);   // 27s
          break;
        case 4:
          printf("std::async x12 test\n");
      // for multithreaded testing:
          f[0] = std::async(std::launch::async, testNN, nullptr);
          f[1] = std::async(std::launch::async, testNN, nullptr);
          f[2] = std::async(std::launch::async, testNN, nullptr);
          f[3] = std::async(std::launch::async, testNN, nullptr);
          f[4] = std::async(std::launch::async, testNN, nullptr);
          f[5] = std::async(std::launch::async, testNN, nullptr);
          f[6] = std::async(std::launch::async, testNN, nullptr);
          f[7] = std::async(std::launch::async, testNN, nullptr);
          f[8] = std::async(std::launch::async, testNN, nullptr);
          f[9] = std::async(std::launch::async, testNN, nullptr);
          f[10] = std::async(std::launch::async, testNN, nullptr);
          f[11] = std::async(std::launch::async, testNN, nullptr);
          break;
      }// case

    }

    time_t runTime = time(nullptr);
    runTime -= start;

    printf("calc done in %lds (%ld calc/s)\n", runTime, TEST_ITERATIONS / runTime);

}