计算 10亿 的和,js 和 c 的处理时长对比

计算 10亿 的和,js 和 c 的处理时长对比

js

4.17s

let sum = 0;
let start = new Date().getTime();
for (let i=0;i<1000000000; i=i+1){
    sum = sum +i;
}
let stop = new Date().getTime();
console.log((stop - start)/1000, sum);

结果:
计算 10亿 的和,js 和 c 的处理时长对比_第1张图片

c

3.65s

#include "stdio.h"
#include "time.h"
#include 


int main() {

    struct timeval start, stop;
    gettimeofday(&start, NULL);
    double sum = 0;
    for (double i=0;i<1000000000; i=i+1){
        sum+=i;
    }
    gettimeofday(&stop, NULL);

    float diffMs = (float )(stop.tv_usec - start.tv_usec)/1000;
    float difS = (float )(stop.tv_sec - start.tv_sec);
    printf("s: %f, ms: %f\n", difS, diffMs);

    if (diffMs < 0){
        difS = difS - 1 + (1 * 1000 + diffMs)/1000;
    } else {
        difS = difS + diffMs/1000;
    }
    printf("sum = %.0f\n", sum);
    printf("diff is : %.3fs", difS);

}

结果:
计算 10亿 的和,js 和 c 的处理时长对比_第2张图片

你可能感兴趣的:(C,javascript,c语言,java)