fork(6) download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <unordered_set>
  5. #include <cstdlib>
  6. #include <ctime>
  7. #include <cassert>
  8.  
  9. typedef unsigned long long ull;
  10. typedef std::pair<int,ull> Hash;
  11.  
  12. struct getHash {
  13. public:
  14. template <typename T, typename U>
  15. std::size_t operator()(const std::pair<T, U> &x) const
  16. {
  17. return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
  18. }
  19. };
  20.  
  21. ull rand_ull() {
  22. ull res = 0;
  23. for (int i = 0; i < 6; ++i) {
  24. (res *= 1000) += (std::rand() % 1000);
  25. }
  26. return res;
  27. }
  28.  
  29. int main() {
  30. std::srand(std::time(0));
  31.  
  32. const int n = (int)4e6;
  33.  
  34. std::vector<Hash> array(n);
  35.  
  36. for (auto& it : array) {
  37. it = std::make_pair(std::rand() % (int)1e9, rand_ull());
  38. }
  39.  
  40. std::vector<Hash> queries(n);
  41.  
  42. for (auto& it : queries) {
  43. it = std::make_pair(std::rand() % (int)1e9, rand_ull());
  44. }
  45.  
  46. double t = clock();
  47.  
  48. std::unordered_set<Hash, getHash> hashtable;
  49.  
  50. for (auto it : array) {
  51. hashtable.insert(it);
  52. }
  53.  
  54. int count1 = 0;
  55.  
  56. for (auto hash : queries) {
  57. count1 += hashtable.find(hash) != hashtable.end();
  58. }
  59.  
  60. double time1 = (clock() - t) / CLOCKS_PER_SEC;
  61.  
  62. t = clock();
  63.  
  64. std::sort(array.begin(), array.end());
  65.  
  66. int count2 = 0;
  67.  
  68. for (auto hash : queries) {
  69. count2 += std::binary_search(array.begin(), array.end(), hash);
  70. }
  71.  
  72. double time2 = (clock() - t) / CLOCKS_PER_SEC;
  73.  
  74. assert(count1 == count2);
  75.  
  76. fprintf(stdout, "size & queries = %d\n", n);
  77. fprintf(stdout, " hashtable = %0.3fs\n", time1);
  78. fprintf(stdout, "sort+binsearch = %0.3fs\n", time2);
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 4.47s 349304KB
stdin
Standard input is empty
stdout
size & queries = 4000000
     hashtable = 2.074s
sort+binsearch = 1.621s