2xtimes slower than cpp

⚓ Rust    📅 2025-08-11    👤 surdeus    👁️ 5      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: 2xtimes slower than cpp

Why? Can someone help? I'm new to rust
Both compiled with optimizations set RUSTFLAGS=-C target-cpu=native -C opt-level=3
cargo build --release
Ran iterations 1000000 and 100 (non harcoded in code for a reason anti optimization)

use std::io::{self, Write};
use std::time::Instant;

fn main() {

    print!("Enter N: ");
    io::stdout().flush().unwrap();
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let n: u64 = buf.trim().parse().expect("invalid N");


    print!("Enter R (number of repetitions): ");
    io::stdout().flush().unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let r: u64 = buf.trim().parse().expect("invalid R");

    let start = Instant::now();

    let mut total: u64 = 0;
    for _ in 0..r {
        for i in 1..=n {
            total = total.wrapping_add(i);
        }
    }

    let elapsed = start.elapsed();
    println!("Time: {:.6} seconds", elapsed.as_secs_f64());
    println!("Result: {}", total);
}

cpp


#include <iostream>
#include <chrono>
#include <cstdint>

int main() {
    std::uint64_t N, R;
    std::cout << "Enter N: ";
    std::cin >> N;
    std::cout << "Enter R (number of repetitions): ";
    std::cin >> R;

    auto start = std::chrono::high_resolution_clock::now();

    std::uint64_t total = 0;
    for (std::uint64_t r = 0; r < R; ++r) {
        for (std::uint64_t i = 1; i <= N; ++i) {
            total += i;
        }
    }

    auto end = std::chrono::high_resolution_clock::now();
    double elapsed = std::chrono::duration<double>(end - start).count();

    std::cout << "Time: " << elapsed << " seconds\n";
    std::cout << "Result: " << total << '\n';
    return 0;
}

5 posts - 4 participants

Read full topic

🏷️ Rust_feed