不同的电脑执行如下代码可能会有不同的结果。但是我在同一台机器上的结果,java会比rust快5倍。
java代码:
java
public class Test {
private static final int MAX = 10000000;
public static void main(String[] args) {
test(1, 3.141592653589793, 2.718281828459045, "Addition");
test(2, 3.141592653589793, 2.718281828459045, "Subtraction");
test(3, 3.141592653589793, 2.718281828459045, "Multiplication");
test(4, 3.141592653589793, 2.718281828459045, "Division");
}
public static void test(int step, double a, double b, String msg) {
long startTime = System.currentTimeMillis();
double sum = 0;
switch (step) {
case 1 -> {
for (int i = 0; i < MAX; i++) {
sum += a + b;
}
}
case 2 -> {
for (int i = 0; i < MAX; i++) {
sum += a - b;
}
}
case 3 -> {
for (int i = 0; i < MAX; i++) {
sum += a * b;
}
}
case 4 -> {
for (int i = 0; i < MAX; i++) {
sum += a / b;
}
}
}
long endTime = System.currentTimeMillis();
System.out.println(msg + " Time taken: " + (endTime - startTime) + "ms result: " + sum);
}
}
java代码的运行结果
bash
Addition Time taken: 15ms result: 5.8598744811975874E7
Subtraction Time taken: 14ms result: 4233108.251312001
Multiplication Time taken: 17ms result: 8.539734223664734E7
Division Time taken: 15ms result: 1.155727349739092E7
rust
fn main() {
_test1(1, 3.141592653589793, 2.718281828459045, "Addition");
_test1(2, 3.141592653589793, 2.718281828459045, "Subtraction");
_test1(3, 3.141592653589793, 2.718281828459045, "Multiplication");
_test1(4, 3.141592653589793, 2.718281828459045, "Division");
}
const MAX: usize = 10000000;
fn _test1(step: u8, a: f64, b: f64, msg: &str) {
let start = std::time::Instant::now();
let mut sum = 0.0;
match step {
1 => {
for _ in 0..MAX {
sum += a + b;
}
}
2 => {
for _ in 0..MAX {
sum += a - b;
}
}
3 => {
for _ in 0..MAX {
sum += a * b;
}
}
4 => {
for _ in 0..MAX {
sum += a / b;
}
}
_ => {
println!("Invalid step");
}
}
println!("{} Time take: {:?}ms result: {}", msg, start.elapsed().as_millis(), sum);
}
bash
Addition Time take: 82ms result: 58598744.811975874
Subtraction Time take: 75ms result: 4233108.251312001
Multiplication Time take: 73ms result: 85397342.23664734
Division Time take: 70ms result: 11557273.49739092