doume1301 2014-07-03 20:39
浏览 1093
已采纳

Golang:如何有效确定文件中的行数?

In Golang, I am looking for an efficient way to determine the number of lines a file has.

Of course, I can always loop through the entire file, but does not seem very efficient.

file, _ := os.Open("/path/to/filename")
fileScanner := bufio.NewScanner(file)
lineCount := 0
for fileScanner.Scan() {
    lineCount++
}
fmt.Println("number of lines:", lineCount)

Is there a better (quicker, less expensive) way to find out how many lines a file has?

  • 写回答

3条回答 默认 最新

  • doutuan4361 2014-07-03 21:54
    关注

    Here's a faster line counter using bytes.Count to find the newline characters.

    It's faster because it takes away all the extra logic and buffering required to return whole lines, and takes advantage of some assembly optimized functions offered by the bytes package to search characters in a byte slice.

    Larger buffers also help here, especially with larger files. On my system, with the file I used for testing, a 32k buffer was fastest.

    func lineCounter(r io.Reader) (int, error) {
        buf := make([]byte, 32*1024)
        count := 0
        lineSep := []byte{'
    '}
    
        for {
            c, err := r.Read(buf)
            count += bytes.Count(buf[:c], lineSep)
    
            switch {
            case err == io.EOF:
                return count, nil
    
            case err != nil:
                return count, err
            }
        }
    }
    

    and the benchmark output:

    BenchmarkBuffioScan   500      6408963 ns/op     4208 B/op    2 allocs/op
    BenchmarkBytesCount   500      4323397 ns/op     8200 B/op    1 allocs/op
    BenchmarkBytes32k     500      3650818 ns/op     65545 B/op   1 allocs/op
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看