简体   繁体   English

为什么 Golang for 循环比 Python for 循环慢?

[英]Why Golang for loop is slower than Python for loop?

I have tested how golang performs on for loop我已经测试了 golang 在 for 循环上的执行情况

Just looping 50,000 times in python and golang and I found that it took 0.59 seconds in python while in golang it took 9.12 seconds仅在 python 和 golang 中循环 50,000 次,我发现在 python 中花费了 0.59 秒,而在 golang 中花费了 9.12 秒

Can any experienced go developer tell me why Golang is too slow at for loop while it's a compiled language?任何有经验的 go 开发人员可以告诉我为什么 Golang 在 for 循环中太慢,而它是一种编译语言?


import (
    "fmt"
    "time"
)
func main()  {
    start := time.Now()

    for i := 0; i < 50000; i++ {
         fmt.Println("Index", i)
    }

    finish := time.Now().Sub(start).Seconds()
    fmt.Printf("Elapsed time was %.2f seconds.\n", finish)
}

You're not measuring what you think you're measuring, that's why you're getting "surprising" results.你没有测量你认为你正在测量的东西,这就是为什么你会得到“令人惊讶”的结果。

You're timing how long it takes to format and print a string, rather than "how fast a for loop is".您正在计时格式化和打印字符串需要多长时间,而不是“for 循环有多快”。

Also, keep in mind that measuring how long it takes to print something depends not only on how the code gets compiled / interpreted, but also on where exactly you're printing: I/O performance depends on things that are beyond your program (maybe the OS, maybe some physical device etc).此外,请记住,衡量打印某些内容需要多长时间不仅取决于代码的编译/解释方式,还取决于您打印的确切位置:I/O 性能取决于您的程序之外的内容(也许操作系统,也许是一些物理设备等)。

Finally, if you tried to microbenchmark the performance of a loop that does absolutely nothing, a compiler could be able to detect that and simply optimize the loop out completely, leaving you with not measuring anything...最后,如果您尝试对完全不执行任何操作的循环的性能进行微基准测试,编译器可以检测到这一点并简单地完全优化循环,让您无需测量任何东西......

These micro-benchmarks in isolation are, most of the time, not useful.在大多数情况下,这些孤立的微基准是没有用的。 If you want to compare Python vs Go in terms of performance, it's usually a better idea to test on a real problem rather than something artificial.如果您想在性能方面比较 Python 和 Go,通常最好测试一个实际问题而不是人工测试。 And then compare not only the raw performance, but also other characteristics of the code quality in general.然后不仅比较原始性能,还比较一般代码质量的其他特征。

The bottom line is that there's too much wrong with this benchmark to get any useful conclusions.最重要的是,这个基准有太多错误,无法得出任何有用的结论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM