Java的比C快 [英] Java faster than C

查看:321
本文介绍了Java的比C快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我做了一个简单的测试来比较Java和C之间的速度 - 一个简单的循环,使一个整数i的增量从0一二十亿

我真的很期待C语言会比Java快。我很惊讶的结果:

它以秒为Java中的时间:约的。 1.8

它以秒为c中的时间:约的。 3.6 秒。

我不认为Java是一种速度更快的语言在所有,但我也不明白为什么循环快两倍为C在我简单的程序?

难道我在做节目的一个关键misstake?或者是MinGW的编译器可配置不好的东西?

 公共类Jrand { 公共静态无效的主要(字串[] args){    长STARTTIME = System.currentTimeMillis的();
    INT I;
    对于(i = 0; I< 20亿;我++){
        // 没做什么!
    }
    长ENDTIME = System.currentTimeMillis的();
    浮动TOTALTIME =(结束时间 - 的startTime);    的System.out.println(时间:+ TOTALTIME / 1000);
 }}

的C程序

 #包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&time.h中GT;
诠释主(){    clock_t表示的startTime;
    STARTTIME =时钟();    INT I;
    对于(i = 0; I< = 20亿;我++){
        // 没做什么
    }
    clock_t表示结束时间;
    ENDTIME =时钟();    浮TOTALTIME =结束时间 - 的startTime;
    的printf(%F,TOTALTIME / 1000);    返回0;
}


解决方案

重建您的C版本比其他任何优化级别 -O0 (如 -O2 ),你会发现它0秒运行一次。所以Java版本需要1.6秒什么也不做,而C版本需要0.0秒(实际上,围绕0.00005秒)什么都不做。

Today I made a simple test to compare the speed between java and c - a simple loop that makes an integer "i" increment from 0 to two billion.

I really expected c-language to be faster than java. I was surprised of the outcome:

the time it takes in seconds for java: approx. 1.8 seconds

the time it takes in seconds for c: approx. 3.6 seconds.

I DO NOT think that java is a faster language at all, but I DO NOT either understand why the loop is twice as fast as c in my simple programs?

Did I made a crucial misstake in the program? Or is the compiler of MinGW badly configurated or something?

public class Jrand {

 public static void main (String[] args) {

    long startTime = System.currentTimeMillis();
    int i; 
    for (i = 0; i < 2000000000; i++) {
        // Do nothing!
    }
    long endTime = System.currentTimeMillis();
    float totalTime = (endTime - startTime);

    System.out.println("time: " + totalTime/1000);
 }

}

THE C-PROGRAM

#include<stdio.h>
#include<stdlib.h>
#include <time.h>
int main () {

    clock_t startTime;
    startTime = clock();

    int i;
    for (i = 0; i <= 2000000000; i++) {
        // Do nothing
    }
    clock_t endTime;
    endTime = clock();

    float totalTime = endTime - startTime;
    printf("%f", totalTime/1000);

    return 0;
}

解决方案

Rebuild your C version with any optimization level other than -O0 (e.g. -O2) and you will find it runs in 0 seconds. So the Java version takes 1.6 seconds to do nothing, and the C version takes 0.0 seconds (really, around 0.00005 seconds) to do nothing.

这篇关于Java的比C快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆