Working with cpp std::unordered_set, I noticed running time is much longer than I expected. Comparing it to Python brings those suprising results:
C++:
<code>#include <iostream>
#include <chrono>
#include <unordered_set>
#include <cmath>
#define TIME std::chrono::high_resolution_clock::now()
#define PRINT_DURATION(start,end, MEASURE_NAME) std::cout << "Runtime of " << MEASURE_NAME << ": "
<< ((std::chrono::duration<double>)(end - start)).count() << " seconds" << std::endl
using namespace std;
const int ITERS = pow(10,7);
int main(){
auto start = TIME;
unordered_set<int> s;
for (int i=0; i < ITERS; i++){
s.insert(i);
}
auto end = TIME;
cout << "Set size is: " << s.size() << endl;
PRINT_DURATION(start,end, "Unordered Set");
return 0;
}
</code>
<code>#include <iostream>
#include <chrono>
#include <unordered_set>
#include <cmath>
#define TIME std::chrono::high_resolution_clock::now()
#define PRINT_DURATION(start,end, MEASURE_NAME) std::cout << "Runtime of " << MEASURE_NAME << ": "
<< ((std::chrono::duration<double>)(end - start)).count() << " seconds" << std::endl
using namespace std;
const int ITERS = pow(10,7);
int main(){
auto start = TIME;
unordered_set<int> s;
for (int i=0; i < ITERS; i++){
s.insert(i);
}
auto end = TIME;
cout << "Set size is: " << s.size() << endl;
PRINT_DURATION(start,end, "Unordered Set");
return 0;
}
</code>
#include <iostream>
#include <chrono>
#include <unordered_set>
#include <cmath>
#define TIME std::chrono::high_resolution_clock::now()
#define PRINT_DURATION(start,end, MEASURE_NAME) std::cout << "Runtime of " << MEASURE_NAME << ": "
<< ((std::chrono::duration<double>)(end - start)).count() << " seconds" << std::endl
using namespace std;
const int ITERS = pow(10,7);
int main(){
auto start = TIME;
unordered_set<int> s;
for (int i=0; i < ITERS; i++){
s.insert(i);
}
auto end = TIME;
cout << "Set size is: " << s.size() << endl;
PRINT_DURATION(start,end, "Unordered Set");
return 0;
}
Output:
Runtime of Unordered Set: 1.32282 seconds
while in python:
<code>import time
t = time.time()
s = set()
for i in range(10**7):
s.add(i)
len(s)
print("Runtime is:", time.time()-t)
</code>
<code>import time
t = time.time()
s = set()
for i in range(10**7):
s.add(i)
len(s)
print("Runtime is:", time.time()-t)
</code>
import time
t = time.time()
s = set()
for i in range(10**7):
s.add(i)
len(s)
print("Runtime is:", time.time()-t)
Output:
Runtime is: 0.6965017318725586
Compilation of cpp program was done by default g++ compiling. With optimization flags, runtime drastically to about ~0.5 seconds. Maybe as was expected for c++ program.
Where I am wrong?