经过我测试,还是C比较快一点,但是差距不大。
测试环境如下
Linux o-s 4.6.4-1-ARCH #1 SMP PREEMPT Mon Jul 11 19:12:32 CEST 2016 x86_64 GNU/Linux
Intel(R) Core(TM) i7-4500U CPU @ 1.80GHz
8GB DDR3内存
java -showversion
openjdk version "1.8.0_112"
OpenJDK Runtime Environment (build 1.8.0_112-b15)
OpenJDK 64-Bit Server VM (build 25.112-b15, mixed mode)
gcc 版本 6.2.1 20160830 (GCC)
线程模型:posix
C冒泡排序测试
下面是C的代码,排序部分没有变。计时部分稍微修改了一下。
#include
#include
#include
#include
void bubbleSort(int* a,int length);
int main()
{
srand(time(NULL));
int array[100000];
for (int i = 0; i < 100000; i ++) {
array[i] = rand();
}
clock_t starttime, endtime;
double duration;
starttime = clock();
bubbleSort(array,100000);
endtime = clock();
duration = (double)(endtime -starttime)*1000.0/CLOCKS_PER_SEC;
printf("use %f\n",duration);
return 0;
}
void bubbleSort(int* a,int length)
{
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}
}
编译运行
/home/o/111 [o@o-s] [11:29]
> gcc Sort.c -o Sort -O2
/home/o/111 [o@o-s] [11:30]
> ./Sort
use 15548.507000
使用clang编译
/home/o/111 [o@o-s] [12:06]
> clang-3.8 Sort.c -O2 -o Sort
/home/o/111 [o@o-s] [12:06]
> ./Sort
use 13214.605000
java冒泡排序测试
java代码如下
没有修改计时代码,还是使用的System.currentTimeMillis(),使用System.nanoTime()精度会比较高。
import java.util.Random;
public class Sort {
public static void main(String[] args) {
Random random = new Random();
int[] array = new int[100000];
for (int i = 0; i < 100000; i ++) {
array[i] = random.nextInt(100000);
}
long start = System.currentTimeMillis();
bubbleSort(array);
System.out.println("use " + (System.currentTimeMillis() - start));
}
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;
}
}
}
}
}
运行测试(修改使用-server参数)
/home/o/111 [o@o-s] [11:45]
> javac -server Sort.java
/home/o/111 [o@o-s] [12:02]
> java Sort
use 19018