3
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <sys/mman.h>
#include <time.h>

#define HUGEPAGE 2048*1024
void *normal_malloc(int len)
{
    void *ptr = malloc(len);
    bzero(ptr, len);
    return ptr;
}

void *trans_malloc(int len)
{
    void *ptr = NULL;
    int ret = posix_memalign(&ptr, HUGEPAGE, len);
    if(ret) perror("posix_memalign");
    ret = madvise(ptr, len, MADV_HUGEPAGE);
    bzero(ptr, len);
    return ptr;
}

void *mmap_malloc(int len)
{
    void *ptr = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_HUGETLB, -1,0);
    return ptr;
}

int main(int argc, char **argv)
{
    char *ptr = NULL;
    int len = HUGEPAGE*256;
    srand(time(NULL));
    switch(argc){
        case 1: ptr = normal_malloc(len);break;
        case 2: ptr = trans_malloc(len);break;
        case 3: ptr = mmap_malloc(len); break;
    }

    long j = 0;
    for(int i=0;i<len;i++){
        j += ptr[rand()%len];
    }
    return 0;
}

I use normal malloc and posix_memalign and mmap to test performance. My test result is : malloc cost about 29.7s, posix_memalign cost about 23.5s, and mmap is very near with malloc. Both posix_memalign and mmap uses hugepages. Why one has obvious improvement, the other not? Do I use mmap in the wrong way? I don't do bzero for mmap since the man pages says "its contents are initialized to zero".

Mr Pang
  • 1,083
  • 1
  • 8
  • 20

0 Answers0