我不明白golang怎么在这个操作上比c++快10倍,甚至go中的map查找比c++快3倍。
这是 C++ 片段
#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());
}
这是 golang 片段:
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))
}
我想知道的是如何优化 c++ 以获得更好的性能。
蝴蝶不菲
繁花不似锦
大话西游666
相关分类