四季花海
和 Max 一样,我强烈怀疑 Go 的缓慢与糟糕的 I/O 性能有关。我测试了这个假设:package mainimport "fmt"import "os"import "time"func main(){ now := time.Now() input,_ := os.Open("testing/test_cases.txt") defer input.Close() output,_ := os.Create("testing/Goutput.txt") defer output.Close() var ncases int var p float64 fmt.Fscanf(input,"%d",&ncases) fmt.Println("Opened files in ", time.Since(now), "seconds") now = time.Now() cases := make([]float64, ncases) fmt.Println("Made array in ", time.Since(now), "seconds") now = time.Now() for i := 0; i < ncases; i++ { fmt.Fscanf(input,"%f",&cases[i]) } fmt.Println("Read data in ", time.Since(now), "seconds") now = time.Now() for i := 0; i < ncases; i++ { p = cases[i] if p >= 0.5 { cases[i] = 10000 * (1-p) * (2*p-1) + 10000 } else { cases[i] = p*(1-2*p)*10000 + 10000 } } fmt.Println("Processed data in ", time.Since(now), "seconds") now = time.Now() for i := 0; i < ncases; i++ { fmt.Fprintln(output, cases[i]) } fmt.Println("Output processed data in ", time.Since(now), "seconds")}运行它产生了这个输出:在 2.011228ms 秒内打开文件在 109.904us 秒内制作阵列4.524544608s秒读取数据10.083329ms 秒内处理的数据1.703542918s秒输出处理数据所以看起来在我的机器上,所有的数学运算都发生在大约 10 毫秒内,但 I/O 很慢,证实了假设。正如 Janne 在评论中指出的那样,可能有比fmt.更新:例如,包装input和outputwithbufio的读者和作家:binput := bufio.NewReader(input)boutput := bufio.NewWriter(output)使用binput和boutput缓冲 I/O,您的原始版本在我的机器上运行时间为 2.1 秒,比 Python 的 2.7 快一些。更新 2:我注意到通过切换到缓冲 I/O 会得到不同的结果。事实证明,您还需要调整格式字符串以包含\n,就像您在 C 版本中所做的那样。我认为这实际上更正确,但看起来你可以在没有缓冲的情况下逃脱。这对Flush()你的缓冲输出也很重要,我做了但之前没有提到。这是我完整的缓冲解决方案:package mainimport "fmt"import "os"import "bufio"import "time"func main(){ now := time.Now() nbinput, _ := os.Open("testing/test_cases.txt") defer nbinput.Close() nboutput, _ := os.Create("testing/Goutput.txt") defer nboutput.Close() binput := bufio.NewReader(nbinput) boutput := bufio.NewWriter(nboutput) var ncases int var gain, p float64 fmt.Fscanf(binput,"%d\n",&ncases) for i := 0; i < ncases; i++ { fmt.Fscanf(binput, "%f\n", &p) if p >= 0.5 { gain = 10000 * (1-p) * (2*p -1) } else { gain = p*(1-2*p)*10000 } fmt.Fprintln(boutput, gain+10000) } boutput.Flush() fmt.Println("Took ", time.Since(now), "seconds")}