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.3 kB
9
Indexable
/**
 * 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
 */

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

#define TEST_ITERATIONS 100*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(){
    time_t start = time(nullptr);

    { // for future to join thread

      int testVariant = 2;
      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);

}