在编程中有许多语言,而不同的编程语言有时候也能实现相同的功能,那么不同语言之间的运行速度有多少差别呢?这里选择 实验这里使用三种语言进行矩阵乘法。 矩阵的大小为2048 x 2048(即每个矩阵的乘法和加法运算为8,589,934,592),我为它们填充了0.0到1.0之间的随机值(使用随机值而不是对所有三种语言使用完全相同的矩阵的影响可以忽略不计)。每个实验运行了五次,并计算了平均运行时间。 1.C代码 #include <stdlib.h> #include <stdio.h> #include <time.h> #define n 2048 double A[n][n]; double B[n][n]; double C[n][n]; int main() { //populate the matrices with random values between 0.0 and 1.0 for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { A[i][j] = (double) rand() / (double) RAND_MAX; B[i][j] = (double) rand() / (double) RAND_MAX; C[i][j] = 0; } } struct timespec start, end; double time_spent; //matrix multiplication clock_gettime(CLOCK_REALTIME, &start); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { C[i][j] += A[i][k] * B[k][j]; } } } clock_gettime(CLOCK_REALTIME, &end); time_spent = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000000.0; printf("Elapsed time in seconds: %f \n", time_spent); return 0; } 2.Java代码 import java.util.Random; public class MatrixMultiplication { static int n = 2048; static double[][] A = new double[n][n]; static double[][] B = new double[n][n]; static double[][] C = new double[n][n]; public static void main(String[] args) { //populate the matrices with random values between 0.0 and 1.0 Random r = new Random(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { A[i][j] = r.nextDouble(); B[i][j] = r.nextDouble(); C[i][j] = 0; } } long start = System.nanoTime(); //matrix multiplication for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { C[i][j] += A[i][k] * B[k][j]; } } } long stop = System.nanoTime(); double timeDiff = (stop - start) * 1e-9; System.out.println("Elapsed time in seconds: " + timeDiff); } } 3.python代码 import random import time n = 2048 #populate the matrices with random values between 0.0 and 1.0 A = [[random.random() for row in range(n)] for col in range(n)] B = [[random.random() for row in range(n)] for col in range(n)] C = [[0 for row in range(n)] for col in range(n)] start = time.time() #matrix multiplication for i in range(n): for j in range(n): for k in range(n): C[i][j] += A[i][k] * B[k][j] end = time.time() print("Elapsed time in seconds %0.6f" % (end-start)) 如何编译与运行#C gcc MatrixMultiplication.c -o matrix ./matrix #Java javac MatrixMultiplication.java java MatrixMultiplication #Python python MatrixMultiplication.py 运行时间根据这些结果, 等待!!! 实际上,这是不公平的比较。 当我们编译Java程序时,即使没有任何优化标志, 因此,在编译 gcc -O2 MatrixMultiplication.c -o matrix./matrixgcc -O3 MatrixMultiplication.c -o matrix./matrix 新的运行时间现在, 总结结果讨论结果
以上就是关于三门编程语言的比较结论。 |
|
来自: 昵称33618363 > 《待分类》