sample.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // spreadsort sorting example
  2. //
  3. // Copyright Steven Ross 2009-2014.
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. // See http://www.boost.org/libs/sort for library home page.
  9. #include <boost/sort/spreadsort/spreadsort.hpp>
  10. #include <time.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <algorithm>
  14. #include <vector>
  15. #include <string>
  16. #include <fstream>
  17. #include <sstream>
  18. #include <iostream>
  19. using namespace boost::sort::spreadsort;
  20. #define DATA_TYPE int
  21. //Pass in an argument to test std::sort
  22. int main(int argc, const char ** argv) {
  23. size_t uCount,uSize=sizeof(DATA_TYPE);
  24. bool stdSort = false;
  25. unsigned loopCount = 1;
  26. for (int u = 1; u < argc; ++u) {
  27. if (std::string(argv[u]) == "-std")
  28. stdSort = true;
  29. else
  30. loopCount = atoi(argv[u]);
  31. }
  32. std::ifstream input("input.txt", std::ios_base::in | std::ios_base::binary);
  33. if (input.fail()) {
  34. printf("input.txt could not be opened\n");
  35. return 1;
  36. }
  37. double total = 0.0;
  38. std::vector<DATA_TYPE> array;
  39. input.seekg (0, std::ios_base::end);
  40. size_t length = input.tellg();
  41. uCount = length/uSize;
  42. //Run multiple loops, if requested
  43. for (unsigned u = 0; u < loopCount; ++u) {
  44. input.seekg (0, std::ios_base::beg);
  45. //Conversion to a vector
  46. array.resize(uCount);
  47. unsigned v = 0;
  48. while (input.good() && v < uCount)
  49. input.read(reinterpret_cast<char *>(&(array[v++])), uSize );
  50. if (v < uCount)
  51. array.resize(v);
  52. clock_t start, end;
  53. double elapsed;
  54. start = clock();
  55. if (stdSort)
  56. std::sort(array.begin(), array.end());
  57. else
  58. boost::sort::spreadsort::spreadsort(array.begin(), array.end());
  59. end = clock();
  60. elapsed = static_cast<double>(end - start);
  61. std::ofstream ofile;
  62. if (stdSort)
  63. ofile.open("standard_sort_out.txt", std::ios_base::out |
  64. std::ios_base::binary | std::ios_base::trunc);
  65. else
  66. ofile.open("boost_sort_out.txt", std::ios_base::out |
  67. std::ios_base::binary | std::ios_base::trunc);
  68. if (ofile.good()) {
  69. for (unsigned v = 0; v < array.size(); ++v) {
  70. ofile.write(reinterpret_cast<char *>(&(array[v])), sizeof(array[v]) );
  71. }
  72. ofile.close();
  73. }
  74. total += elapsed;
  75. array.clear();
  76. }
  77. input.close();
  78. if (stdSort)
  79. printf("std::sort elapsed time %f\n", total / CLOCKS_PER_SEC);
  80. else
  81. printf("spreadsort elapsed time %f\n", total / CLOCKS_PER_SEC);
  82. return 0;
  83. }