niklas-heer / speed-comparison

A repo which compares the speed of different programming languages.
https://niklas-heer.github.io/speed-comparison
MIT License
511 stars 79 forks source link

how come in my bench, javascript is 2 times faster than rust? #132

Closed 0xF48 closed 3 weeks ago

0xF48 commented 3 weeks ago

js ->


function calculatePi(iterations) {
    let pi = 0;
    let sign = 1;

    for (let i = 0; i < iterations; i++) {
        pi += sign / (2 * i + 1);
        sign *= -1;  // Alternate the sign
    }

    return pi * 4;  // Multiply the result by 4
}

const iterations = 1000000000;  // Number of iterations for the approximation

// Start measuring time
const start = Date.now();

const pi = calculatePi(iterations);

// Stop measuring time
const duration = Date.now() - start;

console.log(`Approximation of Pi after ${iterations} iterations: ${pi}`);
console.log(`Time taken: ${duration} ms`);

rust ->

use std::time::Instant;

fn main() {
    let iterations = 1000000000;  // Number of iterations for the approximation
    let mut pi: f64 = 0.0;
    let mut sign = 1.0;

    // Start measuring time
    let start = Instant::now();

    for i in 0..iterations {
        pi += sign / (2.0 * i as f64 + 1.0);
        sign *= -1.0;  // Alternate the sign
    }

    pi *= 4.0;  // Multiply the result by 4

    // Stop measuring time
    let duration = start.elapsed();

    println!("Approximation of Pi after {} iterations: {}", iterations, pi);
    println!("Time taken: {:?}", duration);
}
0xF48 commented 3 weeks ago

nvm i had to build it for production