how can I efficiently read numbers from stdin in Go (or why fmt.Scanf is so inefficient)

huangapple go评论89阅读模式
英文:

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秒)。

那么为什么会这么慢,我应该如何正确地读取intuint64float64类型的数据呢?

英文:

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

huangapple
  • 本文由 发表于 2015年5月1日 16:07:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/29983559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定