1. 程式人生 > >幾種語言循環1000000000次的時間

幾種語言循環1000000000次的時間

nds main double println num tdi turn 3.0 int

先申明這個並不是測試各種語言的好壞,頂多是和編譯優化程度有關。

c語言:

#include <stdio.h>
#include <time.h>


int main(void) {


long a=0;
clock_t start, stop;

double duration;

start = clock();
for(int i=0;i<1000000000;i++){
a++;
}
stop = clock();
duration = ((double)(stop - start))/CLOCKS_PER_SEC;
printf("%f",duration);

return 0;
}

結果是2.9s

c++

#include <iostream>
#include <time.h>
using namespace std;

int main() {
long a=0;
clock_t start, ends;

double duration;

start = clock();
for(int i=0;i<1000000000;i++){
a++;
}
ends = clock();

cout <<"Running Time : "<<(double)(ends - start)/ CLOCKS_PER_SEC << endl;

return 0;
}

結果 3.0s

php7:

<?php


$t1 = microtime(true);
for($i=0;$i<1000000000;$i++){

}
$t2 = microtime(true);
echo ‘耗時‘.round($t2-$t1,3).‘秒‘;



?>

結果是11s

java 1.8:

import java.io.*;
import java.lang.*;
import java.util.*;
class test
{




public static void main (String[] args) throws java.lang.Exception
{
long start= System.currentTimeMillis();
long a=0;
for(long i=0;i<1000000000;i++){
a++;
}
long end= System.currentTimeMillis();

System.out.println(a);
System.out.println(end-start);
}
}

結果是 0.449s

nodejs:

var start = new Date().getTime();

var a=0;
for(var i=0;i<1000000000;i++){
a++;
}

var end = new Date().getTime();

console.log((end - start)+"ms") ;

結果是 1.17s

c#:

using System;
using System.Diagnostics;
public class Test
{
public static void Main()
{
Stopwatch sw = new Stopwatch();

long a=0;
sw.Start();

for(long i=0;i<1000000000;i++){
a++;
}

sw.Stop();
TimeSpan ts2 = sw.Elapsed;
Console.WriteLine("Stopwatch總共花費{0}ms.", ts2.TotalMilliseconds);
}
}

結果0.541s

groovy:

using System;
using System.Diagnostics;
public class Test
{
public static void Main()
{
Stopwatch sw = new Stopwatch();

long a=0;
sw.Start();

for(long i=0;i<1000000000;i++){
a++;
}

sw.Stop();
TimeSpan ts2 = sw.Elapsed;
Console.WriteLine("Stopwatch總共花費{0}ms.", ts2.TotalMilliseconds);
}
}

結果:6.2s

python3 :

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import time
# from numba import jit
#
#
# @jit
def test():
a=0



start=time.time()
while a < 1000000000:
a=a+1
end=time.time()

print (end-start)

print (a)

if __name__=="__main__":
test()

結果 90s

不過以上python代碼去掉jit的註釋使用jit編譯後執行結果是 0.035s

幾種語言循環1000000000次的時間