fork(60) download
  1. #include <cstdlib>
  2. #include <vector>
  3.  
  4. #include <iostream>
  5. #include <string>
  6.  
  7. #include <chrono>
  8.  
  9. class TestTimer
  10. {
  11. public:
  12. using clock = std::chrono::high_resolution_clock;
  13. using time_point = clock::time_point;
  14. using duration = clock::duration;
  15. TestTimer(const std::string & name) : name(name),
  16. start(clock::now())
  17. {
  18. }
  19.  
  20. ~TestTimer()
  21. {
  22. time_point now(clock::now());
  23. duration d = now - start;
  24.  
  25. std::cout << name << " completed in " << d.count() * (double)duration::period::num / duration::period::den <<
  26. " seconds" << std::endl;
  27. }
  28.  
  29. private:
  30. std::string name;
  31. time_point start;
  32. };
  33.  
  34. struct Pixel
  35. {
  36. Pixel()
  37. {
  38. }
  39.  
  40. Pixel(unsigned char r, unsigned char g, unsigned char b) : r(r), g(g), b(b)
  41. {
  42. }
  43.  
  44. unsigned char r, g, b;
  45. };
  46.  
  47. void UseVector()
  48. {
  49. TestTimer t("UseVector");
  50.  
  51. for(int i = 0; i < 1000; ++i)
  52. {
  53. int dimension = 999;
  54.  
  55. std::vector<Pixel> pixels;
  56. pixels.resize(dimension * dimension);
  57.  
  58. for(int i = 0; i < dimension * dimension; ++i)
  59. {
  60. pixels[i].r = 255;
  61. pixels[i].g = 0;
  62. pixels[i].b = 0;
  63. }
  64. }
  65. }
  66.  
  67. void UseVectorPushBack()
  68. {
  69. TestTimer t("UseVectorPushBack");
  70.  
  71. for(int i = 0; i < 1000; ++i)
  72. {
  73. int dimension = 999;
  74.  
  75. std::vector<Pixel> pixels;
  76. pixels.reserve(dimension * dimension);
  77.  
  78. for(int i = 0; i < dimension * dimension; ++i)
  79. pixels.push_back(Pixel(255, 0, 0));
  80. }
  81. }
  82.  
  83. void UseArray()
  84. {
  85. TestTimer t("UseArray");
  86.  
  87. for(int i = 0; i < 1000; ++i)
  88. {
  89. int dimension = 999;
  90.  
  91. Pixel * pixels = (Pixel *)malloc(sizeof(Pixel) * dimension * dimension);
  92.  
  93. for(int i = 0 ; i < dimension * dimension; ++i)
  94. {
  95. pixels[i].r = 255;
  96. pixels[i].g = 0;
  97. pixels[i].b = 0;
  98. }
  99.  
  100. free(pixels);
  101. }
  102. }
  103.  
  104. int main()
  105. {
  106. TestTimer t1("The whole thing");
  107.  
  108. UseArray();
  109. //UseVector();
  110. //UseVectorPushBack();
  111.  
  112. return 0;
  113. }
Success #stdin #stdout 3.69s 3432KB
stdin
Standard input is empty
stdout
UseArray completed in 3.70414 seconds
The whole thing completed in 3.70429 seconds