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

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

Golang: How do I determine the number of lines in a file efficiently?

问题

在Golang中,我正在寻找一种高效的方法来确定文件的行数。

当然,我可以始终循环遍历整个文件,但这似乎不太高效。

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

有没有更好(更快、更省资源)的方法来确定文件有多少行?

英文:

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?

答案1

得分: 80

这是一个使用bytes.Count来查找换行符的更快的行计数器。

它更快是因为它消除了返回整行所需的所有额外逻辑和缓冲,并利用了字节切片中的一些汇编优化函数,提供了字节包来搜索字符。

较大的缓冲区在这里也很有帮助,特别是对于较大的文件。在我的系统上,使用于测试的文件,32k的缓冲区是最快的。

func lineCounter(r io.Reader) (int, error) {
    buf := make([]byte, 32*1024)
    count := 0
    lineSep := []byte{'\n'}

    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
        }
    }
}

以及基准测试的输出:

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
英文:

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{'\n'}

	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

得分: 9

我找到的最有效的方法是使用字节包的IndexByte函数,它的速度至少比使用bytes.Count快四倍,并且根据缓冲区的大小使用的内存要少得多。

func LineCounter(r io.Reader) (int, error) {

    var count int
    const lineBreak = '\n'

    buf := make([]byte, bufio.MaxScanTokenSize)

    for {
        bufferSize, err := r.Read(buf)
        if err != nil && err != io.EOF {
            return 0, err
        }

        var buffPosition int
        for {
            i := bytes.IndexByte(buf[buffPosition:], lineBreak)
            if i == -1 || bufferSize == buffPosition {
                break
            }
            buffPosition += i + 1
            count++
        }
        if err == io.EOF {
            break
        }
    }

    return count, nil
}

基准测试结果:

BenchmarkIndexByteWithBuffer  2000000       653 ns/op    1024 B/op       1 allocs/op
BenchmarkBytes32k             500000        3189 ns/op   32768 B/op       1 allocs/op
英文:

The most efficient way I found is using IndexByte of the byte packet, it is at least four times faster than using bytes.Count and depending on the size of the buffer it uses much less memory.

func LineCounter(r io.Reader) (int, error) {

	var count int
	const lineBreak = '\n'

	buf := make([]byte, bufio.MaxScanTokenSize)

	for {
		bufferSize, err := r.Read(buf)
		if err != nil && err != io.EOF {
			return 0, err
		}

		var buffPosition int
		for {
			i := bytes.IndexByte(buf[buffPosition:], lineBreak)
			if i == -1 || bufferSize == buffPosition {
				break
			}
			buffPosition += i + 1
			count++
		}
		if err == io.EOF {
			break
		}
	}

	return count, nil
}

Benchmark

BenchmarkIndexByteWithBuffer  2000000	       653 ns/op	    1024 B/op	       1 allocs/op
BenchmarkBytes32k             500000	      3189 ns/op	   32768 B/op	       1 allocs/op

答案3

得分: -2

没有比你的方法更快的方法,因为没有关于文件有多少行的元数据。你可以通过手动查找换行符来稍微提速:

func lineCount(r io.Reader) (int, error) {
    buf := make([]byte, 8192)
    var n int

    for {
        c, err := r.Read(buf)
        if err != nil {
            if err == io.EOF && c == 0 {
                break
            } else {
                return n, err
            }
        }

        for _, b := range buf[:c] {
            if b == '\n' {
                n++
            }
        }
    }

    if err == io.EOF {
        err = nil
    }

    return n, err
}

这段代码会逐个读取缓冲区中的字节,并计算换行符的数量。最后返回行数和可能的错误。

英文:

There is no approach that is significantly faster than yours as there is no meta-data on how many lines a file has. You could reach a little speed up by manually looking for newline-characters:

func lineCount(r io.Reader) (int n, error err) {
    buf := make([]byte, 8192)

    for {
        c, err := r.Read(buf)
        if err != nil {
            if err == io.EOF && c == 0 {
                break
            } else {
                return
            }
        }

        for _, b := range buf[:c] {
            if b == '\n' {
                n++
            }
        }
    }

    if err == io.EOF {
        err = nil
    }
}

huangapple
  • 本文由 发表于 2014年7月4日 04:39:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/24562942.html
匿名

发表评论

匿名网友

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

确定