dpgkg42484 2016-03-25 17:50
浏览 35
已采纳

在Go中使用GMP风格的性能处理大量数据

I'm learning Go and I started using the math/big package to deal with arbitrary-length integer.

I wrote this program that computes the n-th Fibonacci number : (removed the imports) :

func main() {
    imax, _ := strconv.Atoi(os.Args[1])
    var a, b, c big.Int
    a.SetUint64(0)
    b.SetUint64(1)
    for i := 0; i < imax; i++ {
        c.Set(&b)
        b.Add(&b, &a)
        a.Set(&c)
    }
    fmt.Println(a.String())
}

Here's the code for the C program :

int main(int argc, char** argv)
{
    int imax = atoi(argv[1]);

    mpz_t a, b, c;
    mpz_inits(a, b, c, NULL);
    mpz_set_ui(a, 0);
    mpz_set_ui(b, 1);

    int i = 0;
    for (i = 0; i < imax; i++) {
        mpz_swap(a, b);
        mpz_add(b, a, b);
    }

    char* astr = NULL;
    astr = mpz_get_str(NULL, 10, a);
    printf("%s
", astr);

    return EXIT_SUCCESS;
}

The Go program computes the term 100,000 in 0.1 second (average), while the C equivalent, using the GMP lib, runs in 0.04 second only. That's two times slower.

Is there a way to get the same performance in my Go program ?

  • 写回答

2条回答 默认 最新

  • douqian1517 2016-03-25 18:24
    关注

    Don't print to stdout, it's slow. What result do you get for this code?

    package main
    
    import (
        "math/big"
        "os"
        "strconv"
    )
    
    func main() {
        max, err := strconv.Atoi(os.Args[1])
        if err != nil {
            panic(err)
        }
        a, b := big.NewInt(0), big.NewInt(1)
        for i := 0; i < max; i++ {
            a.Add(a, b)
            a, b = b, a
        }
    }
    

    Go is not hand crafted assembler code.

    Your value of 100,000 is too small for a reliable benchmark. Use 1,000,000 or another value that runs for at least ten seconds.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)