Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

10.8 KB
Raw Blame
//! Copy engines side by side: rustyfiles' (`fastcopy`), Windows' own (what File Explorer and Files use), robocopy (one thread and
//! 16), and FastCopy and TeraCopy when they are named, on sets of files from the C: drive to folders on other drives.
//!
//!     cargo run --release -p rf-win --example copy_bench -- [--runs 3] [--sets small,mixed,big] [--to C:,E:,F:] [--tools ...]
//!
//! FastCopy and TeraCopy are named by `RF_BENCH_FASTCOPY` and `RF_BENCH_TERACOPY` (their .exe). The sets are made once in
//! `%LOCALAPPDATA%\rf-bench-copy\src` (about 7 GB): `small` 10,000 files of 4 KB in 100 folders, `mixed` 150 files of 1 to 40 MB,
//! `big` one 4 GB file. Each destination is `<drive>\rf-bench-copy-dst` (on C: under the source's folder); it is emptied before
//! every copy and removed at the end. Before each set its files are read once, so every tool reads them from the cache alike, and
//! the order of the tools turns every run. A copy counts when the tool says it is done (Windows may still be writing its cache to
//! the disk then, for every tool alike); then the files and bytes at the destination are checked.
//!
//! Also prints what `rf_win::drives::disk_info` says about each drive (bus, model, seek penalty, NVMe host memory buffer).

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant};

const CREATE_NO_WINDOW: u32 = 0x0800_0000;

fn arg(name: &str) -> Option<String> {
    let args: Vec<String> = std::env::args().collect();
    args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
}

/// Deterministic, incompressible-looking bytes.
fn fill(buf: &mut [u8], seed: u64) {
    let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
    for chunk in buf.chunks_mut(8) {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        let b = x.to_le_bytes();
        chunk.copy_from_slice(&b[..chunk.len()]);
    }
}

fn make_set(root: &Path, name: &str) -> PathBuf {
    let dir = root.join(name);
    let done = root.join(format!(".{name}-done"));
    if done.exists() {
        return dir;
    }
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    match name {
        "small" => {
            let mut buf = vec![0u8; 4096];
            for i in 0..10_000u64 {
                let sub = dir.join(format!("d{:03}", i % 100));
                if i < 100 {
                    std::fs::create_dir_all(&sub).unwrap();
                }
                fill(&mut buf, i);
                std::fs::write(sub.join(format!("file{i:05}.bin")), &buf).unwrap();
            }
        }
        "mixed" => {
            for i in 0..150u64 {
                let mb = 1 + (i * 37 % 40);
                let mut buf = vec![0u8; (mb * 1024 * 1024) as usize];
                fill(&mut buf, 1000 + i);
                std::fs::write(dir.join(format!("clip{i:03}.bin")), &buf).unwrap();
            }
        }
        "big" => {
            use std::io::Write;
            let mut f = std::io::BufWriter::with_capacity(8 << 20, std::fs::File::create(dir.join("big.bin")).unwrap());
            let mut buf = vec![0u8; 8 << 20];
            for i in 0..512u64 {
                fill(&mut buf, 5000 + i);
                f.write_all(&buf).unwrap();
            }
        }
        _ => panic!("unknown set {name}"),
    }
    std::fs::write(done, "").unwrap();
    dir
}

/// Files and bytes under `dir`.
fn tally(dir: &Path) -> (u64, u64) {
    let (mut files, mut bytes) = (0, 0);
    let mut stack = vec![dir.to_path_buf()];
    while let Some(d) = stack.pop() {
        for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
            let Ok(m) = e.metadata() else { continue };
            if m.is_dir() {
                stack.push(e.path());
            } else {
                files += 1;
                bytes += m.len();
            }
        }
    }
    (files, bytes)
}

/// Reads every file once, so that each tool finds them in the cache.
fn warm(dir: &Path) {
    let mut stack = vec![dir.to_path_buf()];
    let mut buf = vec![0u8; 8 << 20];
    while let Some(d) = stack.pop() {
        for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
            if e.path().is_dir() {
                stack.push(e.path());
            } else if let Ok(mut f) = std::fs::File::open(e.path()) {
                use std::io::Read;
                while f.read(&mut buf).is_ok_and(|n| n > 0) {}
            }
        }
    }
}

fn run(cmd: &mut Command) -> anyhow::Result<std::process::ExitStatus> {
    use std::os::windows::process::CommandExt;
    Ok(cmd.creation_flags(CREATE_NO_WINDOW).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status()?)
}

/// Copies the folder `src` INTO `dst` (so that `dst\<name>` is the copy), the way of each tool.
fn copy(tool: &str, src: &Path, dst: &Path) -> anyhow::Result<()> {
    let name = src.file_name().unwrap();
    match tool {
        "rustyfiles" => {
            let tracker = Arc::new(rf_win::fileops::Tracker::new(Box::new(|_, _, _| {}), Arc::new(AtomicBool::new(false))));
            anyhow::ensure!(rf_win::fastcopy::transfer(rf_win::fileops::Transfer::Copy, &[src.to_path_buf()], dst, tracker)?, "stopped");
        }
        "windows" => rf_win::bench::shell_copy_quiet(&[src.to_path_buf()], dst)?,
        "robocopy" | "robocopy-mt16" => {
            let mut c = Command::new("robocopy");
            c.arg(src).arg(dst.join(name)).args(["/E", "/NFL", "/NDL", "/NJH", "/NJS", "/NP", "/R:0", "/W:0"]);
            if tool == "robocopy-mt16" {
                c.arg("/MT:16");
            }
            let st = run(&mut c)?;
            anyhow::ensure!(st.code().is_some_and(|c| c < 8), "robocopy exit {st}");
        }
        "fastcopy" => {
            let exe = std::env::var("RF_BENCH_FASTCOPY")?;
            // fcp.exe is FastCopy's own command-line copy (the window version takes /no_ui /auto_close for the same)
            let console = Path::new(&exe).file_name().is_some_and(|n| n.eq_ignore_ascii_case("fcp.exe"));
            let mut c = Command::new(&exe);
            c.arg("/cmd=force_copy");
            if !console {
                c.args(["/no_ui", "/auto_close"]);
            }
            let st = run(c.arg(src).arg(format!("/to={}\\", dst.display())))?;
            anyhow::ensure!(st.success(), "fastcopy exit {st}");
        }
        "teracopy" => {
            let exe = std::env::var("RF_BENCH_TERACOPY")?;
            let st = run(Command::new(exe).arg("Copy").arg(src).arg(dst).args(["/OverwriteAll", "/Close"]))?;
            anyhow::ensure!(st.success(), "teracopy exit {st}");
        }
        t => anyhow::bail!("unknown tool {t}"),
    }
    Ok(())
}

fn median(mut v: Vec<f64>) -> Option<f64> {
    v.sort_by(f64::total_cmp);
    v.get(v.len() / 2).copied()
}

fn main() {
    rf_win::shell::ensure_com();
    let runs: usize = arg("--runs").and_then(|s| s.parse().ok()).unwrap_or(3);
    let sets: Vec<String> = arg("--sets").unwrap_or("small,mixed,big".into()).split(',').filter(|s| !s.is_empty()).map(String::from).collect();
    let drives: Vec<String> = arg("--to").unwrap_or("C:,E:,F:".into()).split(',').filter(|s| !s.is_empty()).map(String::from).collect();
    let mut tools: Vec<String> = arg("--tools").map(|s| s.split(',').map(String::from).collect()).unwrap_or_else(|| {
        vec!["rustyfiles".into(), "windows".into(), "robocopy".into(), "robocopy-mt16".into()]
    });
    if arg("--tools").is_none() {
        for (t, var) in [("fastcopy", "RF_BENCH_FASTCOPY"), ("teracopy", "RF_BENCH_TERACOPY")] {
            if std::env::var_os(var).is_some_and(|p| Path::new(&p).is_file()) {
                tools.push(t.into());
            }
        }
    }
    let root = PathBuf::from(std::env::var("LOCALAPPDATA").unwrap()).join("rf-bench-copy");
    let src_root = root.join("src");
    std::fs::create_dir_all(&src_root).unwrap();

    println!("drives:");
    for d in &drives {
        let i = rf_win::drives::disk_info(Path::new(&format!("{d}\\")));
        println!(
            "  {d} {:?} {:?} seek penalty {:?} removable {} host memory buffer {:?} KiB -> DRAM-less {:?}",
            i.bus,
            i.model.clone().unwrap_or_default(),
            i.seek_penalty,
            i.removable,
            i.host_memory_buffer_kib,
            i.dramless()
        );
    }
    println!("tools: {}", tools.join(", "));

    let mut out = serde_json::Map::new();
    for set in &sets {
        let src = make_set(&src_root, set);
        let (files, bytes) = tally(&src);
        println!("\n== {set}: {files} files, {:.2} GB", bytes as f64 / 1e9);
        let mut row = serde_json::Map::new();
        for drive in &drives {
            let dst = if drive.eq_ignore_ascii_case("C:") { root.join("dst") } else { PathBuf::from(format!("{drive}\\rf-bench-copy-dst")) };
            let mut times: Vec<Vec<f64>> = vec![Vec::new(); tools.len()];
            warm(&src);
            for r in 0..runs {
                for k in 0..tools.len() {
                    // the order turns every run
                    let k = (k + r) % tools.len();
                    let _ = std::fs::remove_dir_all(&dst);
                    std::fs::create_dir_all(&dst).unwrap();
                    std::thread::sleep(Duration::from_secs(2));
                    let t = Instant::now();
                    let res = copy(&tools[k], &src, &dst);
                    let ms = t.elapsed().as_secs_f64() * 1000.0;
                    match res {
                        Ok(()) => {
                            let got = tally(&dst.join(src.file_name().unwrap()));
                            if got == (files, bytes) {
                                times[k].push(ms);
                            } else {
                                println!("  {drive} {}: INCOMPLETE copy {got:?} of {:?}", tools[k], (files, bytes));
                            }
                        }
                        Err(e) => println!("  {drive} {}: {e:#}", tools[k]),
                    }
                }
            }
            let _ = std::fs::remove_dir_all(&dst);
            let mut cell = serde_json::Map::new();
            print!("  to {drive}");
            for (k, t) in tools.iter().enumerate() {
                match median(times[k].clone()) {
                    Some(ms) => {
                        print!("  {t} {:.0} ms ({:.0} MB/s)", ms, bytes as f64 / 1e6 / (ms / 1000.0));
                        cell.insert(t.clone(), serde_json::json!({ "ms": ms, "runs": times[k] }));
                    }
                    None => print!("  {t} -"),
                }
            }
            println!();
            row.insert(drive.clone(), serde_json::Value::Object(cell));
        }
        out.insert(set.clone(), serde_json::Value::Object(row));
    }
    let path = std::env::temp_dir().join("rf-copy-bench.json");
    std::fs::write(&path, serde_json::to_vec_pretty(&serde_json::Value::Object(out)).unwrap()).unwrap();
    println!("\nwritten: {}", path.display());
}