When the copy file golang, buffer set appropriate value much, performance comparison

In the language go, when copy files, large files using buffer buffer, can significantly speed up the time,

But this value is much better?

In addition to considering the hardware resources of the computer, but also consider the size of the CP file.

If you are within 100m of the small files, a CP can be finished.

However, if the file is larger than 1G, construction or set a larger buffer to operate.

 

copy.go

func Copy(src, dst string, BUFFERSIZE int64) error {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return err
	}
	if !sourceFileStat.Mode().IsRegular() {
		return fmt.Errorf("%s is not a regular file.", src)
	}
	source, err := os.Open(src)
	if err != nil {
		return err
	}
	defer source.Close()
	_, ERR = os.Stat (DST)
	if err == nil {
		return fmt.Errorf("File %s already exists.", dst)
	}
	destination, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer destination.Close()
	if err != nil {
		panic(err)
	}
	buf := make([]byte, BUFFERSIZE)
	for {
		n, err := source.Read(buf)
		if err != nil && err != io.EOF {
			return err
		}
		if n == 0 {
			break
		}
		if _, err := destination.Write(buf[:n]); err != nil {
			return err
		}
	}
	return err
}

  

Guess you like

Origin www.cnblogs.com/aguncn/p/12080306.html