c冒泡排序比java慢原因是什么。
高洛峰
高洛峰 2016-10-24 13:36:11
[Java讨论组]

gcc的版本是5.3.0开启编译优化-O2。java是1.8的server模式
a为a[10000]时java耗时50ms。c耗时75ms。
a为十万位是java耗时5秒,c耗时7.5秒。
为什么c会比java慢?有人试过吗?
c的冒泡

void BubbleSort(int a[])
{

    for(int i=0; i<len-1; i++)
    {

        for(int j=0; j<len-1-i; j++)
        {
            if(a[j]>a[j+1])
            {
                int tmp=a[j];
                a[j]=a[j+1];
                a[j+1]=tmp;
            }
        }
    }
}

java code

public static void bubbleSort(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int tmp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = tmp;
                }

            }
        }

    }

下面是完整代码,同志们可以自己机子跑跑看。c的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>
#define GET_ARRAY_LEN(array,len){len = (sizeof(array) / sizeof(array[0]));}
int len;
int main()
{

//    int *a=malloc(300000000*sizeof(int));
//   len=300000000;
//   int a[10000];
//  GET_ARRAY_LEN(a,len);
    int *a=malloc(10000*sizeof(int));
    len=10000;

    for(int i=0; i<len; i++)
    {
        a[i]=len-i;
    }
//print(a);
    struct timeb startTime, endTime;
    ftime(&startTime);
    BubbleSort(a);
    ftime(&endTime);
    printf("%d \n",(endTime.time-startTime.time)*1000 + (endTime.millitm - startTime.millitm));
//print(a);

}

void BubbleSort(int a[])
{

    for(int i=0; i<len-1; i++)
    {

        for(int j=0; j<len-1-i; j++)
        {
            if(a[j]>a[j+1])
            {
                int tmp=a[j];
                a[j]=a[j+1];
                a[j+1]=tmp;
            }
        }
    }
}
void print(int a[])
{

    for(int i=0; i<len; i++)
    {
        printf(" %d",a[i]);
    }
    printf("\n");
}

java 完整代码

public class Sort {
    public static void main(String[] args) {
//         int[] a = getData(500000000);
        int[] a = getData(10000);
        // print(a);
        long start = System.currentTimeMillis();
        bubbleSort(a);
        System.out.println("use " + (System.currentTimeMillis() - start));

        // print(a);
    }

    public static void bubbleSort(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int tmp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = tmp;
                }

            }
        }

    }
}


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(1)
三叔

可能java编译器优化的更好。在leetcode上也时常看得到java的解法优于c/c++的解法。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号