rust-lang / rust-lang/rust

Poor codegen for u64::isqrt()

Open
#150,653 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

I-slow T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by compiling the provided u64::isqrt() example with the reported rustc 1.92.0 toolchain and inspecting the generated instructions. Trace the rustc code-generation path for this operation and compare its output and runtime with the issue's proposed approach; done means the excess instructions and slowdown are addressed with evidence from a focused benchmark.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.