C(使用-O6编译)需要16us或4us来分配2GB内存:
./2d
115
16
./2d
31
4
cat 2d.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
struct timeval tm0,tm1,tm2,tm3;
unsigned short *A,*B;
gettimeofday(&tm0, NULL); A = malloc(2); gettimeofday(&tm1, NULL);
gettimeofday(&tm2, NULL); B = malloc(2000000000); gettimeofday(&tm3, NULL);
printf("%ld\n", 1000000 * (tm1.tv_sec - tm0.tv_sec) + (tm1.tv_usec - tm0.tv_usec) );
printf("%ld\n", 1000000 * (tm3.tv_sec - tm2.tv_sec) + (tm3.tv_usec - tm2.tv_usec) );
}
对于2GB内存的不安全分配,node.js确实需要3ms:
node
> t0=process.hrtime(); var A=new Buffer.allocUnsafe(1); t1=process.hrtime();
[ 11473, 848540243 ]
> t2=process.hrtime(); var B=new Buffer.allocUnsafe(2000000000); t3=process.hrtime();
[ 11473, 860724500 ]
>
> ((t1[1]-t0[1])/1000000000.0+(t1[0]-t0[0]))+" "+
... ((t3[1]-t2[1])/1000000000.0+(t3[0]-t2[0]));
'0.00004601 0.003662583'
> t0=process.hrtime(); var A=new Buffer.allocUnsafe(1); t1=process.hrtime();
[ 11477, 352424752 ]
> t2=process.hrtime(); var B=new Buffer.allocUnsafe(2000000000); t3=process.hrtime();
[ 11477, 357416910 ]
>
> ((t1[1]-t0[1])/1000000000.0+(t1[0]-t0[0]))+" "+
... ((t3[1]-t2[1])/1000000000.0+(t3[0]-t2[0]));
'0.000017987 0.002890688'
>
不应该将Buffer.allocUnsafe()运行时类似于malloc()吗? https://nodejs.org/api/buffer.html#buffer_class_method_buffer_allocunsafe_size
赫尔曼。