Newer
Older
Import / research / packing_tests / sizes_test.cpp
#include <cstdint>
#include <cstdio>
#include <vector>
#include <chrono>

class i1
{
public:
    int32_t  b3;
};

class i2
{
public:
    int64_t  b3;
};

class i3
{
public:
    bool     b1;
    int32_t  b3;
};

#pragma pack(1)
class i4
{
public:
    bool     b1;
    int32_t  b3;
};
#pragma pack()

class c1
{
public:
    bool     b1;
    void*    b2;
    int32_t  b3;
    void*    b4;
    bool     b5;
};

class c2
{
public:
    bool     b1;
    bool     b5;
    int32_t  b3;
    void*    b2;
    void*    b4;
};

class c3
{
public:
    void*    b4;
    void*    b2;
    int32_t  b3;
    bool     b5;
    bool     b1;
};

class c4
{
public:
    void*    b1;
    void*    b2;
    int32_t  b3;
    int32_t  b4;
    void*    b5;
    void*    b6;
    void*    b7;
    void*    b8;
    void*    b9;
};


struct Result
{
  uint8_t   size;
  uint64_t  time;
  int64_t   result;
};


template <typename T>
Result test_speed_outter()
{
  std::vector<T> v1;
  for (uint64_t i = 0; i < 10000000; ++i)
  {
    T item;
    item.b3 = i;
    v1.push_back(item);
  }

  std::chrono::system_clock::time_point t1 = std::chrono::system_clock::now();
  int64_t res = 0;
  for (auto& v : v1)
  {
    res += v.b3;
  }
  std::chrono::system_clock::time_point t2 = std::chrono::system_clock::now();

  Result result;
  result.size = sizeof(T);
  result.time = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
  result.result = res;
//  printf("sizeof(T) = %li\n", sizeof(T));
//  printf("duration: %lli\n", c);
  return result;
}

  
template <typename T>
void test_speed()
{
  Result result;
  uint64_t bestTime1 = 1000000000000000;
  uint64_t worstTime1 = 0;
  uint64_t averageTime1 = 0;
  for (int i = 0; i < 20; ++i)
  {
    result = test_speed_outter<T>();
    if (result.time > worstTime1)
      worstTime1 = result.time;
    if (result.time < bestTime1)
      bestTime1 = result.time;
    averageTime1 += result.time;
  }
  averageTime1 /= 20;
  printf("size: %u   best: %llu   worst: %llu   avg: %llu\n", result.size, bestTime1, worstTime1, averageTime1);
}


int main(int argc, char* argv[])
{
  if (argc > 1)
  {
    switch (argv[1][0])
    {
      case '0': test_speed<i1>(); break;
      case '1': test_speed<i2>(); break;
      case '2': test_speed<i3>(); break;
      case '3': test_speed<i4>(); break;
      case '4': test_speed<c1>(); break;
      case '5': test_speed<c2>(); break;
      case '6': test_speed<c3>(); break;
      case '7': test_speed<c4>(); break;
    }
  }
  else
  {
    test_speed<i1>();
    test_speed<i2>();
    test_speed<i3>();
    test_speed<i4>();
    test_speed<c1>();
    test_speed<c2>();
    test_speed<c3>();
    test_speed<c4>();
  }
  return 0;
}