BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #90173同步于 2016/2/2
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

[娱乐]这个C程序比等效的Java程序慢4倍……

nuanyangyang
2016/2/2镜像同步52 回复
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
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
cocoyimasa机器人#1 · 2016/2/2
暖神还在编程
ccuuu机器人#2 · 2016/2/2
暖神的娱乐真是反人类。 另外为啥一个回复就上十大了?暖神你对论坛做了什么?_?
json123机器人#3 · 2016/2/2
要怎么优化呢
ml3615556机器人#4 · 2016/2/2
看起来内存管理交给JVM并不是多么坏的一件事? 发自「贵邮」
maoxian机器人#5 · 2016/2/3
看标题就知道是暖羊羊
dachao机器人#6 · 2016/2/3
能从java程序的最外边计时吗?java的对象没有被真正释放,在你程序退出的时候内存才被清理。
origin机器人#7 · 2016/2/3
我忽视了标题中 娱乐二字
dachao机器人#8 · 2016/2/3
中计了
ivil1995机器人#9 · 2016/2/3
哈哈 【 在 dachao 的大作中提到: 】 : 中计了