在实际工作,我们需要读取大数据文件,文件可能上g百g,所以我们不可能一次性的读取到内存,io.readall不可用,那么我们可以考虑分块,io流的方式如io.copy.
对比两者:
io.readall:
io.readall 是一个方便的函数,可以将整个文件内容一次性读取到内存中,并返回一个字节切片。这在处理小文件或者需要一次性加载数据的情况下非常适用。然而,对于大文件,使用 io.readall 可能会导致以下问题:
- 内存消耗:读取大文件可能导致内存消耗急剧增加,甚至超出可用内存限制。
- 性能问题:应用程序的响应性可能下降,用户可能会感到应用程序不再响应。
- 延迟问题:大文件的读取需要更多时间,可能导致较长的延迟。
io.copy:
io.copy 函数通过逐块的方式从源读取数据并将其写入目标,适用于流式传输大文件。它具有以下优势:
- 低内存消耗:io.copy 逐块处理数据,不需要将整个文件加载到内存中,从而降低内存消耗。
- 高性能:流式传输提高了读取和写入的效率,适用于需要高性能处理大文件的情况。
- 更好的响应性:io.copy 不会一次性阻塞等待整个文件读取完成,从而提高应用程序的响应性
示例:
package test
import (
"fmt"
"io"
"os"
"runtime"
"testing"
)
func largefileread(_file string) {
f, err := os.open(_file)
if err != nil {
fmt.errorf("打开文件错误:%v", err)
return
}
defer f.close()
// 读取数据大写
buffer := make([]byte, 4096)
for {
getmemory()
n, err := f.read(buffer)
if err != nil && err != io.eof {
fmt.errorf("读取文件错误:%v", err)
return
}
if n == 0 {
break
}
fmt.println("内容:", string(buffer))
}
fmt.println("读取完成")
}
func getmemory() {
// 获取内存信息
var m runtime.memstats
runtime.readmemstats(&m)
fmt.printf("%d kb\n", m.alloc/1024)
}
func test_largefileread(t *testing.t) {
filename := "d:xxxx.txt"
largefileread(filename)
}运行结果:

实时内存占用:854kb,文件大小102m
拓展:golang并发读取超大文件
当今世界的任何计算机系统每天都会生成大量的日志或数据。随着系统的发展,将调试数据存储到数据库中是不可行的,因为它们是不可变的,并且只能用于分析和解决故障。所以大部分公司倾向于将日志存储在文件中,而这些文件通常位于本地磁盘中。
我们将使用go语言,从一个大小为16gb的.txt或.log文件中提取日志。
让我们开始编码……
首先,我们打开文件。对于任何文件的io,我们都将使用标准的go库os.file。
f, err := os.open(filename)
if err != nil {
fmt.println("cannot able to read the file", err)
return
}
// update: close after checking error
defer file.close() //do not forget to close the file
打开文件后,我们有以下两个选项可以选择:
- 逐行读取文件,这有助于减少内存紧张,但需要更多的时间。
- 一次将整个文件读入内存并处理该文件,这将消耗更多内存,但会显著减少时间。
由于文件太大,即16 gb,因此无法将整个文件加载到内存中。但是第一种选择对我们来说也是不可行的,因为我们希望在几秒钟内处理文件。
但你猜怎么着,还有第三种选择。瞧……相比于将整个文件加载到内存中,在go语言中,我们还可以使用bufio.newreader()将文件分块加载。
r := bufio.newreader(f)
for {
buf := make([]byte,4*1024) //the chunk size
n, err := r.read(buf) //loading chunk into buffer
buf = buf[:n]
if n == 0 {
if err != nil {
fmt.println(err)
break
}
if err == io.eof {
break
}
return err
}
}
一旦我们将文件分块,我们就可以分叉一个线程,即go routine,同时处理多个文件区块。上述代码将修改为:
//sync pools to reuse the memory and decrease the preassure on garbage collector
linespool := sync.pool{new: func() interface{} {
lines := make([]byte, 500*1024)
return lines
}}
stringpool := sync.pool{new: func() interface{} {
lines := ""
return lines
}}
slicepool := sync.pool{new: func() interface{} {
lines := make([]string, 100)
return lines
}}
r := bufio.newreader(f)
var wg sync.waitgroup //wait group to keep track off all threads
for {
buf := linespool.get().([]byte)
n, err := r.read(buf)
buf = buf[:n]
if n == 0 {
if err != nil {
fmt.println(err)
break
}
if err == io.eof {
break
}
return err
}
nextuntillnewline, err := r.readbytes('\n')//read entire line
if err != io.eof {
buf = append(buf, nextuntillnewline...)
}
wg.add(1)
go func() {
//process each chunk concurrently
//start -> log start time, end -> log end time
processchunk(buf, &linespool, &stringpool, &slicepool, start, end)
wg.done()
}()
}
wg.wait()
}
上面的代码,引入了两个优化点:
- sync.pool是一个强大的对象池,可以重用对象来减轻垃圾收集器的压力。我们将重用各个分片的内存,以减少内存消耗,大大加快我们的工作。
- go routines帮助我们同时处理缓冲区块,这大大提高了处理速度。
现在让我们实现processchunk函数,它将处理以下格式的日志行。
2020-01-31t20:12:38.1234z, some field, other field, and so on, till new line,...\n
我们将根据命令行提供的时间戳提取日志。
func processchunk(chunk []byte, linespool *sync.pool, stringpool *sync.pool, slicepool *sync.pool, start time.time, end time.time) {
//another wait group to process every chunk further
var wg2 sync.waitgroup
logs := stringpool.get().(string)
logs = string(chunk)
linespool.put(chunk) //put back the chunk in pool
//split the string by "\n", so that we have slice of logs
logsslice := strings.split(logs, "\n")
stringpool.put(logs) //put back the string pool
chunksize := 100 //process the bunch of 100 logs in thread
n := len(logsslice)
noofthread := n / chunksize
if n%chunksize != 0 { //check for overflow
noofthread++
}
length := len(logsslice)
//traverse the chunk
for i := 0; i < length; i += chunksize {
wg2.add(1)
//process each chunk in saperate chunk
go func(s int, e int) {
for i:= s; i<e;i++{
text := logsslice[i]
if len(text) == 0 {
continue
}
logparts := strings.splitn(text, ",", 2)
logcreationtimestring := logparts[0]
logcreationtime, err := time.parse("2006-01- 02t15:04:05.0000z", logcreationtimestring)
if err != nil {
fmt.printf("\n could not able to parse the time :%s for log : %v", logcreationtimestring, text)
return
}
// check if log's timestamp is inbetween our desired period
if logcreationtime.after(start) && logcreationtime.before(end) {
fmt.println(text)
}
}
textslice = nil
wg2.done()
}(i*chunksize, int(math.min(float64((i+1)*chunksize), float64(len(logsslice)))))
//passing the indexes for processing
}
wg2.wait() //wait for a chunk to finish
logsslice = nil
}
对上面的代码进行基准测试。以16 gb的日志文件为例,提取日志所需的时间约为25秒。
完整的代码示例如下:
func main() {
s := time.now()
args := os.args[1:]
if len(args) != 6 { // for format logextractor.exe -f "from time" -t "to time" -i "log file directory location"
fmt.println("please give proper command line arguments")
return
}
starttimearg := args[1]
finishtimearg := args[3]
filename := args[5]
file, err := os.open(filename)
if err != nil {
fmt.println("cannot able to read the file", err)
return
}
defer file.close() //close after checking err
querystarttime, err := time.parse("2006-01-02t15:04:05.0000z", starttimearg)
if err != nil {
fmt.println("could not able to parse the start time", starttimearg)
return
}
queryfinishtime, err := time.parse("2006-01-02t15:04:05.0000z", finishtimearg)
if err != nil {
fmt.println("could not able to parse the finish time", finishtimearg)
return
}
filestat, err := file.stat()
if err != nil {
fmt.println("could not able to get the file stat")
return
}
filesize := filestat.size()
offset := filesize - 1
lastlinesize := 0
for {
b := make([]byte, 1)
n, err := file.readat(b, offset)
if err != nil {
fmt.println("error reading file ", err)
break
}
char := string(b[0])
if char == "\n" {
break
}
offset--
lastlinesize += n
}
lastline := make([]byte, lastlinesize)
_, err = file.readat(lastline, offset+1)
if err != nil {
fmt.println("could not able to read last line with offset", offset, "and lastline size", lastlinesize)
return
}
logslice := strings.splitn(string(lastline), ",", 2)
logcreationtimestring := logslice[0]
lastlogcreationtime, err := time.parse("2006-01-02t15:04:05.0000z", logcreationtimestring)
if err != nil {
fmt.println("can not able to parse time : ", err)
}
if lastlogcreationtime.after(querystarttime) && lastlogcreationtime.before(queryfinishtime) {
process(file, querystarttime, queryfinishtime)
}
fmt.println("\ntime taken - ", time.since(s))
}
func process(f *os.file, start time.time, end time.time) error {
linespool := sync.pool{new: func() interface{} {
lines := make([]byte, 250*1024)
return lines
}}
stringpool := sync.pool{new: func() interface{} {
lines := ""
return lines
}}
r := bufio.newreader(f)
var wg sync.waitgroup
for {
buf := linespool.get().([]byte)
n, err := r.read(buf)
buf = buf[:n]
if n == 0 {
if err != nil {
fmt.println(err)
break
}
if err == io.eof {
break
}
return err
}
nextuntillnewline, err := r.readbytes('\n')
if err != io.eof {
buf = append(buf, nextuntillnewline...)
}
wg.add(1)
go func() {
processchunk(buf, &linespool, &stringpool, start, end)
wg.done()
}()
}
wg.wait()
return nil
}
func processchunk(chunk []byte, linespool *sync.pool, stringpool *sync.pool, start time.time, end time.time) {
var wg2 sync.waitgroup
logs := stringpool.get().(string)
logs = string(chunk)
linespool.put(chunk)
logsslice := strings.split(logs, "\n")
stringpool.put(logs)
chunksize := 300
n := len(logsslice)
noofthread := n / chunksize
if n%chunksize != 0 {
noofthread++
}
for i := 0; i < (noofthread); i++ {
wg2.add(1)
go func(s int, e int) {
defer wg2.done() //to avaoid deadlocks
for i := s; i < e; i++ {
text := logsslice[i]
if len(text) == 0 {
continue
}
logslice := strings.splitn(text, ",", 2)
logcreationtimestring := logslice[0]
logcreationtime, err := time.parse("2006-01-02t15:04:05.0000z", logcreationtimestring)
if err != nil {
fmt.printf("\n could not able to parse the time :%s for log : %v", logcreationtimestring, text)
return
}
if logcreationtime.after(start) && logcreationtime.before(end) {
//fmt.println(text)
}
}
}(i*chunksize, int(math.min(float64((i+1)*chunksize), float64(len(logsslice)))))
}
wg2.wait()
logsslice = nil
}
到此这篇关于golang实现大文件读取的代码示例的文章就介绍到这了,更多相关golang大文件读取内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论