I don't understand how golang is outperforming c++ in this operation by 10 times, even the map lookup is 3 times faster in go than c++.
this is the c++ snippet
#include <iostream>
#include <unordered_map>
#include <chrono>
std::chrono::nanoseconds elapsed(std::chrono::steady_clock::time_point start) {
std::chrono::steady_clock::time_point now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
}
void make_map(int times) {
std::unordered_map<double, double> hm;
double c = 0.0;
for (int i = 0; i < times; i++) {
hm[c] = c + 10.0;
c += 1.0;
}
}
int main() {
std::chrono::steady_clock::time_point start_time = std::chrono::high_resolution_clock::now();
make_map(10000000);
printf("elapsed %lld", elapsed(start_time).count());
}
this is the golang snippet:
func makeMap() {
o := make(map[float64]float64)
var i float64 = 0
x := time.Now()
for ; i <= 10000000; i++ {
o[i] = i+ 10
}
TimeTrack(x)
}
func TimeTrack(start time.Time) {
elapsed := time.Since(start)
// Skip this function, and fetch the PC and file for its parent.
pc, _, _, _ := runtime.Caller(1)
// Retrieve a function object this functions parent.
funcObj := runtime.FuncForPC(pc)
// Regex to extract just the function name (and not the module path).
runtimeFunc := regexp.MustCompile(`^.*\.(.*)$`)
name := runtimeFunc.ReplaceAllString(funcObj.Name(), "$1")
log.Println(fmt.Sprintf("%s took %s", name, elapsed))
}
What I'd like to know is how to optimize the c++ to achieve better performance.