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 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度