fork(1) download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <vector>
  4. #include <string>
  5. #include <map>
  6. #include <unordered_map>
  7. #include <sys/time.h>
  8. using namespace std;
  9.  
  10. class StopWatch {
  11. public:
  12. StopWatch(string title)
  13. : title_(title) {
  14. gettimeofday(&s_, 0);
  15. }
  16. ~StopWatch() {
  17. gettimeofday(&e_, 0);
  18. printf("%s time = %lf\n", title_.c_str(), (e_.tv_sec - s_.tv_sec) + (e_.tv_usec - s_.tv_usec)*1.0E-6);
  19. }
  20. private:
  21. struct timeval s_, e_;
  22. string title_;
  23. };
  24.  
  25. const int COUNT = 100000;
  26.  
  27. int main() {
  28. // your code goes here
  29. {
  30. StopWatch sw("vector");
  31. std::vector<int> v;
  32. for (int i = 0; i < COUNT; i++) {
  33. v.push_back(i);
  34. }
  35. }
  36. {
  37. StopWatch sw("reserved vector");
  38. std::vector<int> v;
  39. v.reserve(COUNT);
  40. for (int i = 0; i < COUNT; i++) {
  41. v.push_back(i);
  42. }
  43. }
  44. std::map<std::string, int> m;
  45. {
  46. StopWatch sw("map set");
  47. for (int i = 0; i < COUNT; i++) {
  48. std::stringstream ss;
  49. ss << i << ":";
  50. m[ss.str()] = i;
  51. }
  52. }
  53. std::unordered_map<std::string, int> um;
  54. {
  55. StopWatch sw("unordered map set");
  56. for (int i = 0; i < COUNT; i++) {
  57. std::stringstream ss;
  58. ss << i << ":";
  59. um[ss.str()] = i;
  60. }
  61. }
  62. {
  63. StopWatch sw("map get");
  64. int total = 0;
  65. for (int i = 0; i < COUNT; i++) {
  66. std::stringstream ss;
  67. ss << i << ":";
  68. total += m[ss.str()];
  69. }
  70. }
  71. {
  72. StopWatch sw("unordered map get");
  73. int total = 0;
  74. for (int i = 0; i < COUNT; i++) {
  75. std::stringstream ss;
  76. ss << i << ":";
  77. total += um[ss.str()];
  78. }
  79. }
  80. return 0;
  81. }
Success #stdin #stdout 0.95s 13536KB
stdin
Standard input is empty
stdout
vector time = 0.001062
reserved vector time = 0.000563
map set time = 0.245256
unordered map set time = 0.224707
map get time = 0.260892
unordered map get time = 0.204241