Java的VS C(运行时间)编辑:添加code [英] Java vs C (Run time) EDIT: Added Code

查看:194
本文介绍了Java的VS C(运行时间)编辑:添加code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚写了找到与所有质数的程序的上限。

I just wrote a program that finds all the prime numbers with an upper bound.

算法:筛埃拉托色尼的

无论是在C和Java写的。该上限是666014。

Wrote it both in C and Java. The upper bound is 666014.

由于某种原因C给出的结果中超过2.5秒,而Java做它像半秒。

For some reason C gives the result in more than 2.5 seconds, while Java does it in like half a second.

详细内容:


  • 在C中的数组是char类型的

  • The array in C is of type char

Java中的数组是布尔类型

The array in Java is of type boolean

ÇIDE:$ C $个cblocks

C IDE: CodeBlocks

的Java IDE:IntellijIdea社区版

Java IDE: IntellijIdea Community Edition

C code:

#include <stdio.h>

int main() {

    int n = 666013;
    int i;
    int k;

    char a[n];

    for (i = 2; i <= n; i++)
        a[i] = 0;

    for (i = 2; i <= n; i++)
         if ( a[i] == 0 )
         {
            printf("%d\n", i);
            for (k = i + i; k <= n; k += i)
                 a[k] = 1;
         }

    return 0;

}

Java的code:

Java code:

package primes;

public class Prime {

    public static void main(String[] args) {
        long starttime = System.nanoTime();
        final int MAXN = 666013;
        boolean a[] = new boolean[MAXN];

        for (int i = 2; i < a.length; i++)
            a[i] = true;

        for (int i = 2; i < a.length; i++)
            if (a[i])
            {
                System.out.println(i);
                System.out.printf("");
                for (int j = i + i; j < a.length; j += i) {
                    a[j] = false;
                }
            }

        System.out.println(System.nanoTime() - starttime);

    }
}

最后编辑:使用的 System.nanoTime()
Java的给0.35秒

Last used System.nanoTime() Java gives 0.35 seconds

的C算法不能有任何更快。这是什么原因Java是更快吗?

The C algorithm cannot be any faster. What is the reason Java is faster here?

推荐答案

我要打赌,你实际上问的,即使你在你的问题的头上市编译时间运行时间。如果你想一次编译,它真的苹果和橘子,特别是如果你在IDE中这样做,而不是使用命令行。

I'm going to bet that you're actually asking about run-time even though you listed compilation time in your question header. If you're trying to time compilation, its really apples to oranges, especially if you're doing it in IDEs instead of using command line.

如果您要比较的Java应用到C ++应用程序,有很多事情你必须考虑的问题。

If you're comparing a Java application to a C++ application, there's a lot of things you must consider.


  • 您应该使用相同的数据类型。

  • 您必须确保你的Java code未触发额外的拳击。

  • 您应该阅读两种语言,并找到如何使用最准确的低级系统定时器。 System.currentTimeMillis的()不是用Java很准确,例如

  • 您应该确保你的时间前将其投入产出所以在这两种语言的输出差异并不在测试测量得到测量。

  • 您是否运行在两种语言相同的架构? (32位或64位)。

坦率地说,你的评价是非常code依赖。而不显示code的人也帮不了你。有很多很多的事情可以做,影响时序,即使在最简单的code。

Frankly, your assessment is very code dependent. Without showing code people can't help you. There are many, many things you could do to affect timings in even the simplest code.

这篇关于Java的VS C(运行时间)编辑:添加code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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