简体   繁体   English

为什么 C 比 Java 慢得多?

[英]Why is C is much slower as compared to Java?

So, I am completely new to C.所以,我对 C 完全陌生。 I am testing the performance of the languages.我正在测试语言的性能。

What I did?我做了什么?

I wrote 2 programs one in C one in java both doing the same thing but C is very slow as compared to Java? I wrote 2 programs one in C one in java both doing the same thing but C is very slow as compared to Java?

Here are the programs:以下是程序:

main.c : main.c

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

void work();

int main() {
    time_t seconds;     
    seconds = time(NULL); 
    printf("time1 : %ld\n", seconds);
    work();
    seconds = time(NULL); 
    printf("time2 : %ld\n", seconds);
    return 0;
}

void work() {
    int a[1000][500];
    for (int k = 0; k < 10000; ++k) {
        for (int i = 0; i < 1000; ++i) {
            for (int j = 0; j < 500; ++j) { 
                a[i][j] = (i + j) * 5416585;
            }
        }
    }
}

Main.java主.java

public class Main {
    public static void main(String[] args) {
        System.out.println("time1 : " + (System.currentTimeMillis() / 1000));
        work();
        System.out.println("time2 : " + (System.currentTimeMillis() / 1000));
    }

    public static void work() {
        int a[][] = new int[1000][500];
        for (int k = 0; k < 10000; ++k) {
            for (int i = 0; i < 1000; ++i) {
                for (int j = 0; j < 500; ++j) { 
                    a[i][j] = (i + j) * 5416585;
                }
            }
        }
    }
}

My Question:-我的问题:-

So, my question is by all what I have read C should be much faster as it is low level whereas Java itself runs on a Virtual Machine thus should be comparatively slower: But in my case the outputs were : -所以,我的问题是我读过的所有内容 C 应该快得多,因为它是低级别的,而 Java 本身在虚拟机上运行因此应该相对较慢:但在我的情况下,输出是: -

C:\>gcc main.c

C:\>javac Main.java

C:\>a
time1 : 1610049457
time2 : 1610049468

C:\>java Main
time1 : 1610049474
time2 : 1610049478

C:\>a
time1 : 1610049487
time2 : 1610049498

C:\>java Main
time1 : 1610049501
time2 : 1610049505

Clearly Java is much faster than C here!显然 Java 比 C 快得多!

Why is this happening?为什么会这样?

By default, GCC does not apply any optimizations, so the generated code is quite slow.默认情况下,GCC 没有应用任何优化,因此生成的代码很慢。 In contrast, Java VMs enable most optimizations by default.相比之下,Java VM 默认启用大多数优化。

$ gcc main.c
$ time ./a.out 
time1 : 1610050160
time2 : 1610050167

real    0m7.113s
user    0m7.112s
sys 0m0.000s
$ gcc -O2 main.c
$ time ./a.out 
time1 : 1610050172
time2 : 1610050172

real    0m0.002s
user    0m0.002s
sys 0m0.000s

If you look at the generated assembler code, the body of the work function is optimized away in the optimized version:如果您查看生成的汇编代码, work function 的主体在优化版本中被优化掉了:

work:
.LFB12:
    .cfi_startproc
    ret
    .cfi_endproc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM