W_Engine_Team_Study

WETSort.cpp 3.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // WETSort.cpp : This file contains the 'main' function. Program execution begins and ends there.
  2. //
  3. #include "pch.h"
  4. #include <random>
  5. #include <chrono>
  6. #include <ratio>
  7. #include <algorithm>
  8. #include <vector>
  9. #pragma pack(push, 1)
  10. template <size_t s>
  11. struct Element
  12. {
  13. int8_t buffer;
  14. bool operator < (const Element& other) const
  15. {
  16. const int8_t* p0 = &buffer;
  17. const int8_t* p1 = &other.buffer;
  18. for (size_t i = 0; i < s; ++i)
  19. {
  20. int n = p0 - p1;
  21. if (n)
  22. return n > 0;
  23. p0++;
  24. p1++;
  25. }
  26. return false;
  27. }
  28. };
  29. #pragma pack(pop)
  30. template <typename ElementType>
  31. double Sort0(const ElementType* data, size_t numItems)
  32. {
  33. std::vector<ElementType> items;
  34. items.reserve(numItems);
  35. for (size_t i = 0; i < numItems; ++i)
  36. {
  37. items.push_back(data[i]);
  38. }
  39. std::chrono::high_resolution_clock clock;
  40. using sec = std::chrono::duration<double, std::ratio<1, 1>>;
  41. auto start = clock.now();
  42. std::sort(items.begin(), items.end(), std::less<ElementType>());
  43. auto end = clock.now();
  44. return std::chrono::duration_cast<sec>(end - start).count();
  45. }
  46. void RunTest(size_t size)
  47. {
  48. std::random_device rdev;
  49. std::default_random_engine re(rdev());
  50. std::uniform_int_distribution<unsigned short> dist(0, 0xff);
  51. if (1)
  52. {
  53. size_t s = 64;
  54. while (s < size)
  55. s <<= 1;
  56. size = s;
  57. }
  58. int32_t* buffer = (int32_t*) malloc(size);
  59. int16_t tmp = 0;
  60. for (size_t i = 0, e = size / sizeof(int32_t); i < e; ++i)
  61. {
  62. int16_t x = dist(re);
  63. int16_t y = (i ^ (tmp << 4)) & 0xff;
  64. tmp = y;
  65. buffer[i] = (x << 16) | y;
  66. }
  67. size_t numItems = size / 4;
  68. double d1 = Sort0(reinterpret_cast<Element<4>*>(buffer), numItems);
  69. printf("std::sort items:%d elapsed:%f\n", numItems, d1);
  70. free(buffer);
  71. }
  72. int main()
  73. {
  74. printf("Sorting 1,000,000 bytes...\n");
  75. RunTest(1000000);
  76. }