From 2d3cc97f78ce6320a099612065a9ba23fb29842b Mon Sep 17 00:00:00 2001 From: MahouShoujoMivutilde <14999778+MahouShoujoMivutilde@users.noreply.github.com> Date: Fri, 14 Jun 2024 08:30:23 +0300 Subject: [PATCH] Use 32KB buffer for `copyFile()` (reduces copy time by 30%) (#1749) * Use 32KB buffer for `copyFile()` (reduces copy time by 30%) This makes `:paste` comparable in performance to `cp --reflink=never` for large files. For large number of small files improvements are less substantial (compared to `cp -r --reflink=never`), though still noticeable. In both cases the copy takes about 30% less time than with `buf` size at 4096. 32KB is the same number `io.Copy()` uses internally (when it can), and is about where improvements stop. Context: https://github.com/gokcehan/lf/issues/1685#issuecomment-2163934296 * Apply suggested changes * Just delete incomplete an file on all errors * Mention new progress UI update frequency * Return the old (each 4MB copied) progress update frequency (progress UI updates don't seem to impact performance much) --- app.go | 4 ++-- copy.go | 42 +++++++++++++++++++++++------------------- 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/app.go b/app.go index a95b1801..87b70574 100644 --- a/app.go +++ b/app.go @@ -332,8 +332,8 @@ func (app *app) loop() { return case n := <-app.nav.copyBytesChan: app.nav.copyBytes += n - // n is usually 4096B so update roughly per 4096B x 1024 = 4MB copied - if app.nav.copyUpdate++; app.nav.copyUpdate >= 1024 { + // n is usually 32*1024B (default io.Copy() buffer) so update roughly per 32KB x 128 = 4MB copied + if app.nav.copyUpdate++; app.nav.copyUpdate >= 128 { app.nav.copyUpdate = 0 app.ui.draw(app.nav) } diff --git a/copy.go b/copy.go index cec83c28..336e5f9a 100644 --- a/copy.go +++ b/copy.go @@ -11,6 +11,24 @@ import ( "github.com/djherbis/times" ) +type ProgressWriter struct { + writer io.Writer + nums chan<- int64 +} + +func NewProgressWriter(writer io.Writer, nums chan<- int64) *ProgressWriter { + return &ProgressWriter{ + writer: writer, + nums: nums, + } +} + +func (progressWriter *ProgressWriter) Write(b []byte) (int, error) { + n, err := progressWriter.writer.Write(b) + progressWriter.nums <- int64(n) + return n, err +} + func copySize(srcs []string) (int64, error) { var total int64 @@ -47,8 +65,6 @@ func copyFile(src, dst string, preserve []string, info os.FileInfo, nums chan in } } - buf := make([]byte, 4096) - r, err := os.Open(src) if err != nil { return err @@ -60,23 +76,11 @@ func copyFile(src, dst string, preserve []string, info os.FileInfo, nums chan in return err } - for { - n, err := r.Read(buf) - if err != nil && err != io.EOF { - w.Close() - os.Remove(dst) - return err - } - - if n == 0 { - break - } - - if _, err := w.Write(buf[:n]); err != nil { - return err - } - - nums <- int64(n) + _, err = io.Copy(NewProgressWriter(w, nums), r) + if err != nil { + w.Close() + os.Remove(dst) + return err } if err := w.Close(); err != nil {