fork download
  1. #include <iostream>
  2. #include <set>
  3. #include <unordered_set>
  4. #include <sys/time.h>
  5. #include <random>
  6. #include <algorithm>
  7.  
  8. namespace better {
  9. template <typename T>struct hash;
  10. template<> struct hash<unsigned> {
  11. std::size_t tables[256][8];
  12.  
  13. template <typename Sseq>
  14. hash(Sseq&& q)
  15. {
  16. std::mt19937 gen(q);
  17. std::generate(&tables[0][0],
  18. &tables[0][0] + sizeof(tables)/sizeof(**tables),
  19. gen);
  20. }
  21.  
  22. std::size_t operator() (unsigned x) const
  23. {
  24. return tables[(x>> 0)&0xff][0]^
  25. tables[(x>> 8)&0xff][1]^
  26. tables[(x>>16)&0xff][2]^
  27. tables[(x>>24)&0xff][3];
  28. }
  29. };
  30. }
  31.  
  32. struct stopwatch {
  33. timeval t1;
  34. const char *s;
  35. stopwatch(const char* s) : s(s) { gettimeofday(&t1, NULL); }
  36. ~stopwatch() {
  37. timeval t2; gettimeofday(&t2, NULL);
  38. timeval d; timersub(&t2, &t1, &d);
  39. std::cout << d.tv_sec << "s "<< d.tv_usec << "ns: " << s <<std::endl;
  40. }
  41. };
  42.  
  43. template <class S>
  44. void test(const char *wat, S&& set)
  45. {
  46. const int tests = 50;
  47. const int insert = 500; // für ideone etwas klener
  48. const int lookup = 500; // das auch
  49.  
  50. stopwatch s(wat);
  51.  
  52. std::mt19937 gen(1);
  53.  
  54. for (int i=0; i<tests; ++i) {
  55. for (int i=0; i<insert; ++i)
  56. set.insert(gen());
  57. for (int i=0; i<lookup; ++i)
  58. set.find(gen());
  59. }
  60. }
  61.  
  62. int main()
  63. {
  64. for (int i=0; i<5; ++i) {
  65. test("std::set", std::set<unsigned>());
  66. test("std::unordered_set", std::unordered_set<unsigned>());
  67. test("std::unordered_set + better:hash",
  68. std::unordered_set<unsigned,better::hash<unsigned>>(0,better::hash<unsigned>(5489u)));
  69. }
  70. }
  71.  
Success #stdin #stdout 0.14s 3436KB
stdin
Standard input is empty
stdout
0s 9958ns: std::set
0s 8035ns: std::unordered_set
0s 7909ns: std::unordered_set + better:hash
0s 9120ns: std::set
0s 8011ns: std::unordered_set
0s 7909ns: std::unordered_set + better:hash
0s 9173ns: std::set
0s 7921ns: std::unordered_set
0s 7925ns: std::unordered_set + better:hash
0s 9071ns: std::set
0s 8017ns: std::unordered_set
0s 7896ns: std::unordered_set + better:hash
0s 9204ns: std::set
0s 8014ns: std::unordered_set
0s 7927ns: std::unordered_set + better:hash