Skip to content

Poor codegen for u64::isqrt() #150653

@10-hard-problems

Description

@10-hard-problems

I tried this code:

fn isqrt(val:u64)->u64{
    val.isqrt()
}

I expected to see this happen: rustc generates reasonable code.

Instead, this happened: rustc generates ~150 too many instructions, which takes a while to run.

Potential fix: Use this implementation instead:

fn isqrt(val:u64)->u64{
    let estimate = (val as f64).sqrt() as u64;
    if val < (1<< 52){//value fits in mantissa, exact precision.
        return estimate; 
    }else{
        // Otherwise, do a newton-raphson iteration for the final bits of precision
        unsafe{assert_unchecked(estimate!=0);};
        return (estimate + val/estimate)/2;
    }
}

On my machine, it ran twice as fast.

Meta

rustc --version --verbose:

rustc 1.92.0 (ded5c06cf 2025-12-08)
binary: rustc
commit-hash: ded5c06cf21d2b93bffd5d884aa6e96934ee4234
commit-date: 2025-12-08
host: x86_64-pc-windows-msvc
release: 1.92.0
LLVM version: 21.1.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.I-slowIssue: Problems and improvements with respect to performance of generated code.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions