fork(2) download
  1. #include <vector>
  2. #include <string>
  3. #include <chrono>
  4. #include <iostream>
  5. #include <random>
  6. #include <algorithm>
  7.  
  8. using namespace std;
  9.  
  10. struct citizen_t {
  11. string first_name;
  12. string last_name;
  13. int salary;
  14. int age;
  15. };
  16.  
  17. struct soa_citizens_t {
  18. vector<string> first_names;
  19. vector<string> last_names;
  20. vector<int> salary;
  21. vector<int> age;
  22.  
  23. void resize( size_t n ) {
  24. first_names.resize( n );
  25. last_names.resize( n );
  26. salary.resize( n );
  27. age.resize( n );
  28. }
  29. };
  30.  
  31. int main() {
  32. using clock_t = chrono::high_resolution_clock;
  33.  
  34. size_t count = 300'000'000;
  35. uniform_int_distribution<int> salary_dist( 0, 10000 );
  36.  
  37. chrono::duration<double> aos_duration;
  38. chrono::duration<double> soa_duration;
  39.  
  40. int aos_avg = 0;
  41. int soa_avg = 0;
  42.  
  43. // Array of Structures
  44. {
  45. const auto seed_val = mt19937::default_seed;
  46. mt19937 rng( seed_val );
  47.  
  48. vector<citizen_t> aos_citizens;
  49. aos_citizens.resize( count );
  50. generate_n( aos_citizens.data(), count, [&]() { citizen_t c; c.salary = salary_dist( rng ); return c; } );
  51.  
  52. auto start = clock_t::now();
  53.  
  54. int avg = 0;
  55. int t = 1;
  56. for ( auto & c : aos_citizens ) {
  57. avg += (c.salary - avg) / t;
  58. ++t;
  59. }
  60.  
  61. auto finish = clock_t::now();
  62. aos_duration = finish - start;
  63. aos_avg = avg;
  64. }
  65.  
  66. // Structure of Arrays
  67. {
  68. const auto seed_val = mt19937::default_seed;
  69. mt19937 rng( seed_val );
  70.  
  71. soa_citizens_t soa_citizens;
  72. soa_citizens.resize( count );
  73. generate_n( soa_citizens.salary.data(), count, [&]() { return salary_dist( rng ); } );
  74.  
  75. auto start = clock_t::now();
  76.  
  77. int avg = 0;
  78. int t = 1;
  79. for ( auto salary : soa_citizens.salary ) {
  80. avg += (salary - avg) / t;
  81. ++t;
  82. }
  83.  
  84. auto finish = clock_t::now();
  85. soa_duration = finish - start;
  86. soa_avg = avg;
  87. }
  88.  
  89. cout << "AoS (" << aos_avg << ") in " << aos_duration.count() << " seconds" << std::endl;
  90. cout << "SoA (" << soa_avg << ") in " << soa_duration.count() << " seconds" << std::endl;
  91.  
  92. return 0;
  93. }
  94.  
Success #stdin #stdout 0.02s 3476KB
stdin
Standard input is empty
stdout
AoS (5010) in 0.00252983 seconds
SoA (5010) in 0.00248755 seconds