Golang 与 Java 的速度

我用 Java 编写了一个程序,用 Go 编写了一个等效程序。我的 Java 程序执行时间约为 5.95 秒,而 Go 程序执行时间约为 41.675789791 秒。虽然 Go 的速度与 C 或 C++ 相当,因为它像 C 一样编译,但为什么会存在如此大的性能差异?程序如下:


围棋程序


package main



import (

    "math"

    "fmt"

    "time"

)


func main() {

    fmt.Printf("vvalue is %v", testFun(10, 16666611, 1000000000))

}


func fun(x float64) float64 {

    return math.Pow(x, 2) - x

}


func testFun(first float64, second float64, times int) float64 {

    var i = 0

    var result float64 = 0

    var dx float64

    dx = (second - first) / float64(times)

    for ; i < times; i++ {

        result += fun(first + float64(i) * dx)

    }

    return result * dx

}   

Java程序


public class Test {

public static void main(String[] args) {

    Test test = new Test();

    double re = test.testFun(10, 16666611, 1000000000);

    System.out.println(re);

}


private double testFun(double first, double second, long times) {

    int i = 0;

    double result = 0;

    double dx = (second - first) / times;

    for (; i < times; i++) {

        result += fun(first + i * dx);

    }

    return result * dx;

}


private double fun(double v) {

    return Math.pow(v, 2) - v;

}

}


湖上湖
浏览 268回答 3
3回答

幕布斯7119047

我建议math.Pow(x,y)在 Go 中实际上没有x^y对ywhile 的整数值进行任何优化,而Math.pow(x,y)只是x*xfor&nbsp;y==2。至少在两个程序pow中用 simple替换时x*x,Java 为 6.5 秒,而 Go 为 1.4 秒。使用pow代替我仍然得到6.5秒为Java而29.4秒了围棋。

喵喵时光机

不要从其他语言翻译。用 Go 编写程序的 Go 版本。例如x*x - x,package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; start := time.Now()&nbsp; &nbsp; v := testFun(10, 16666611, 1000000000)&nbsp; &nbsp; since := time.Since(start)&nbsp; &nbsp; fmt.Printf("value is %v\ntime is %v\n", v, since)}func fun(x float64) float64 {&nbsp; &nbsp; return x*x - x}func testFun(first float64, second float64, times int) float64 {&nbsp; &nbsp; sum := float64(0)&nbsp; &nbsp; dx := (second - first) / float64(times)&nbsp; &nbsp; for i := 0; i < times; i++ {&nbsp; &nbsp; &nbsp; &nbsp; sum += fun(first + float64(i)*dx)&nbsp; &nbsp; }&nbsp; &nbsp; return sum * dx}输出:$ go versiongo version devel +5c11480631 Fri Aug 10 20:02:31 2018 +0000 linux/amd64$ go run speed.govalue is 1.543194272428967e+21time is 1.011965238s$你得到什么结果?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java