dqfxao2898 2019-02-12 19:05
浏览 402
已采纳

go和c ++之间的地图性能比较[关闭]

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.

  • 写回答

3条回答 默认 最新

  • dongzi5673 2019-02-12 20:01
    关注

    Updated to measure similar operations for both cpp and go. It starts measurment before calling the map-making function and ends it when the function returns. Both versions reserve space in the map and return the created map (from which a couple of numbers are printed).

    Slightly modified cpp:

    #include <iostream>
    #include <unordered_map>
    #include <chrono>
    
    std::unordered_map<double, double> make_map(double times) {
        std::unordered_map<double, double> m(times);
    
        for (double c = 0; c < times; ++c) {
            m[c] = c + 10.0;
        }
        return m;
    }
    
    int main() {
        std::chrono::high_resolution_clock::time_point start_time = std::chrono::high_resolution_clock::now();
        auto m = make_map(10000000);
        std::chrono::high_resolution_clock::time_point end_time = std::chrono::high_resolution_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time-start_time);
        std::cout << elapsed.count()/1000000000. << "s
    ";
        std::cout << m[10] << "
    "
                  << m[9999999] << "
    ";    
    }
    
    % g++ -DNDEBUG -std=c++17 -Ofast -o perf perf.cpp
    % ./perf
    2.81886s
    20
    1e+07
    

    Slightly modified go version:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func make_map(elem float64) map[float64]float64 {
        m := make(map[float64]float64, int(elem))
        var i float64 = 0
        for ; i < elem; i++ {
            m[i] = i + 10
        }
        return m
    }
    
    func main() {
        start_time := time.Now()
        r := make_map(10000000)
        end_time := time.Now()
        fmt.Println(end_time.Sub(start_time))
        fmt.Println(r[10])
        fmt.Println(r[9999999])
    }
    
    % go build -a perf.go
    % ./perf
    1.967707381s
    20
    1.0000009e+07
    

    It doesn't look like a tie as it did before the update. One thing slowing the cpp version down is the default hashing function for double. When replacing it with a really bad (but fast) hasher, I got the time down to 1.89489s.

    struct bad_hasher {
        size_t operator()(const double& d) const {
            static_assert(sizeof(double)==sizeof(size_t));
    
            return
                *reinterpret_cast<const size_t*>( reinterpret_cast<const std::byte*>(&d) );
        }
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化