返回信息流CPU:Intel(R) Core(TM) i5-2450M CPU @ 2.50GHz (sandy bridge,4核)
内存:8GB
操作系统:Linux 4.3.3
libc: 2.22-3
jemalloc: 4.0.4
C程序:mass_alloc_test.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SZ 1000000
#define REP 99
typedef struct { int field; } Foo;
int run() {
Foo **ar = (Foo**)calloc(sizeof(Foo*), SZ);
for (int r = 1; r <= REP; r++) {
for (int i = 0; i < SZ; i++) {
int ind = (i * r) % SZ;
Foo *foo = (Foo*)malloc(sizeof(Foo));
foo->field = ar[ind] != NULL ? ar[ind]->field + i : i;
if (ar[ind] != NULL) {
free(ar[ind]);
}
ar[ind] = foo;
}
}
int xor = 0;
for (int i = 0; i < SZ; i++) {
xor ^= ar[i]->field;
free(ar[i]);
}
return xor;
}
int main() {
struct timespec t1, t2;
clock_gettime(CLOCK_REALTIME, &t1);
int result = run();
clock_gettime(CLOCK_REALTIME, &t2);
long diff = 1000000000L*(t2.tv_sec - t1.tv_sec) + (t2.tv_nsec - t1.tv_nsec);
printf("result = %d, time = %ldns\n", result, diff);
return 0;
}
编译和运行:
$ gcc --version
gcc (GCC) 5.3.0
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ gcc -std=gnu11 -Wall -Wpedantic -O3 mass_alloc_test.c -o mass_alloc_test
$ ./mass_alloc_test
result = 105000928, time = 15493611769ns
$ LD_PRELOAD=/usr/lib/libjemalloc.so ./mass_alloc_test
result = 105000928, time = 12613572870ns
Java程序:
package cn.byr.nuanyangyang.alloc;
public class MassAllocTest {
public static final int SZ = 1000000;
public static final int REP = 99;
public static class Foo {
public int field;
}
public static int run() {
Foo[] ar = new Foo[SZ];
for (int r = 1; r <= REP; r++) {
for (int i = 0; i < SZ; i++) {
int ind = (i * r) % SZ;
Foo foo = new Foo();
foo.field = ar[ind] != null ? ar[ind].field + i : i;
ar[ind] = foo;
}
}
int xor = 0;
for (Foo foo : ar) {
xor ^= foo.field;
}
return xor;
}
public static void main(String[] args) {
long t1 = System.nanoTime();
int result = run();
long t2 = System.nanoTime();
System.out.printf("result = %d, time = %dns\n", result, t2 - t1);
}
}
JVM版本:
java -versionopenjdk version "1.8.0_72"
OpenJDK Runtime Environment (build 1.8.0_72-b15)
OpenJDK 64-Bit Server VM (build 25.72-b15, mixed mode)
结果:
result = 105000928, time = 3486176884ns
这是一条镜像帖。来源:北邮人论坛 / cpp / #90173同步于 2016/2/2
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[娱乐]这个C程序比等效的Java程序慢4倍……
nuanyangyang
2016/2/2镜像同步52 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复