英文:
how can I efficiently read numbers from stdin in Go (or why fmt.Scanf is so inefficient)
问题
我开始用Go语言参加编程竞赛(只是为了学习这门语言),令我惊讶的是,以下代码的执行速度非常慢:
var T int
fmt.Scanf("%d", &T)
有多慢呢?读取10^5个整数需要2.5秒(相比之下,Python只需要0.8秒)。
那么为什么会这么慢,我应该如何正确地读取int
、uint64
和float64
类型的数据呢?
英文:
I started to do programming contests in go (just to learn the language) and to my surprise found that
var T int
fmt.Scanf("%d", &T)
is unimaginably slow. How slow? To read 10^5 integers it take me 2.5 seconds (in comparison python does it in 0.8 secs).
So why is it so slow and how should I properly read int
, uint64
and float64
?
答案1
得分: 5
如果您只有整数作为输入,这样应该会更快(尽管未经测试)
package main
import (
"io/ioutil"
"log"
"os"
"strconv"
)
func read() (int64, error) {
b, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return 0, err
}
// 使用 strconv.ParseUint 和 strconv.ParseFloat 类似的方式
return strconv.ParseInt(string(b[:len(b)-1]), 10, 0)
}
func main() {
i, err := read()
if err != nil {
log.Fatal(err)
}
println(i)
}
像这样运行它:
echo 123 | go run main.go
对于交互式输入,您可能希望使用 bufio.NewReader
,参见 https://stackoverflow.com/questions/20895552/how-to-read-input-from-console-line
英文:
If you have only the integer as input, this should be faster (not tested though)
package main
import (
"io/ioutil"
"log"
"os"
"strconv"
)
func read() (int64, error) {
b, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return 0, err
}
// use strconv.ParseUint and strconv.ParseFloat in a similar way
return strconv.ParseInt(string(b[:len(b)-1]), 10, 0)
}
func main() {
i, err := read()
if err != nil {
log.Fatal(err)
}
println(i)
}
run it like this
echo 123 | go run main.go
for interactive input, you might want to use bufio.NewReader, see https://stackoverflow.com/questions/20895552/how-to-read-input-from-console-line
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论