都是Rust的执行速度是最快的。但是我最近做了一个矩阵相乘的测试却得到了诡异的结果!Rust的用时是Java的千倍,完全无法忍受!!!各位大侠请指点一下!到底哪出错了?
Java程序:
package cn.edu.cup;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int size = 1000; // 矩阵大小,可以根据需要进行调整
double[][] matrixA = generateRandomMatrix(size, size);
double[][] matrixB = generateRandomMatrix(size, size);
long startTime = System.currentTimeMillis();
double[][] result = multiplyMatrices(matrixA, matrixB);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("矩阵相乘耗时:" + duration + " 毫秒");
}
// 生成随机矩阵
private static double[][] generateRandomMatrix(int rows, int columns) {
double[][] matrix = new double[rows][columns];
Random random = new Random();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = random.nextDouble();
}
}
return matrix;
}
// 矩阵相乘
private static double[][] multiplyMatrices(double[][] matrixA, double[][] matrixB) {
int rowsA = matrixA.length;
int columnsA = matrixA[0].length;
int columnsB = matrixB[0].length;
double[][] result = new double[rowsA][columnsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < columnsB; j++) {
for (int k = 0; k < columnsA; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
}
运行结果:矩阵相乘耗时:2062 毫秒
Rust代码:
use rand::Rng;
use std::time::{Instant};
fn main() {
let size: usize = 1000; // 矩阵大小,可以根据需要进行调整
let matrix_a = generate_random_matrix(size, size);
let matrix_b = generate_random_matrix(size, size);
let start_time = Instant::now();
let _result = multiply_matrices(&matrix_a, &matrix_b);
let end_time = Instant::now();
let duration = end_time - start_time;
println!("矩阵相乘耗时: {} 毫秒", duration.as_millis());
println!("矩阵相乘耗时: {} 秒", duration.as_millis()/1000);
}
// 生成随机矩阵
fn generate_random_matrix(rows: usize, columns: usize) -> Vec
let mut matrix = vec![vec![0.0; columns]; rows];
let mut rng = rand::thread_rng();
for i in 0..rows {
for j in 0..columns {
matrix[i][j] = rng.gen_range(0.0..1.0);
}
}
matrix
}
// 矩阵相乘
fn multiply_matrices(matrix_a: &Vec
let rows_a = matrix_a.len();
let columns_a = matrix_a[0].len();
let columns_b = matrix_b[0].len();
let mut result = vec![vec![0.0; columns_b]; rows_a];
for i in 0..rows_a {
for j in 0..columns_b {
for k in 0..columns_a {
result[i][j] += matrix_a[i][k] * matrix_b[k][j];
}
}
}
result
}
运行结果:矩阵相乘耗时: 37539 毫秒,矩阵相乘耗时: 37 秒。
各位大侠请指点一下!!
经过知乎大侠们的指点,采用cargo run --release,重新运行,结果:
矩阵相乘耗时: 1942 毫秒 矩阵相乘耗时: 1 秒
这个结果就正常了!
感谢大侠们的指点!!
debug模式与release模式的差异太大了!
好文链接
发表评论