当前位置:网站首页>redis源码学习-02_内存分配
redis源码学习-02_内存分配
2022-06-09 17:52:00 【飞奔的屎壳郎】
redis是一个基于内存的key-value的数据库,其内存管理是非常重要的,为了屏蔽不同平台之间的差异,以及统计内存占用量等,redis对内存分配函数进行了一层封装,程序中统一使用zmalloc,zfree一系列函数,其对应的源码在src/zmalloc.h和src/zmalloc.c两个文件中。
- 在所有申请的指定长度的内存前加了一个sizeof(size_t)的长度(通过一个堆上分配的指针知晓其空间大小)
- 用于记录实际申请的内存长度,
- 方便统计内存使用占用和内存使用状态分析
相关概念
屏蔽底层平台的差异
tcmalloc是Google推出的,https://github.com/gperftools/gperftools
tc_malloc是google开源处理的一套内存管理库,是用C++实现的,TCMalloc给每个线程分配了一个线程局部缓存。小分配可以直接由线程局部缓存来满足。需要的话,会将对象从中央数据结构移动到线程局部缓存中,同时定期的垃圾收集将用于把内存从线程局部缓存迁移回中央数据结构中。
jemalloc是facebook推出的,https://github.com/jemalloc/jemalloc
jemalloc 也是一个内存创管理库,其创始人Jason Evans也是在FreeBSD很有名的开发人员,Jemalloc聚集了malloc的使用过程中所验证的很多技术。忽略细节,从架构着眼,最出色的部分仍是arena和thread cache。
libc是标准的内存分配库malloc和free。
Redis并没有自己实现内存池,没有在标准的系统内存分配器上再加上自己的东西。所以系统内存分配器的性能及碎片率会对Redis造成一些性能上的影响。
redis为了屏蔽不同系统(库)的差异进行了如下预处理:
A,若系统中存在Google的TC_MALLOC库,则使用tc_malloc一族函数代替原本的malloc一族函数。
B,若系统中存在FaceBook的JEMALLOC库,则使用je_malloc一族函数代替原本的malloc一族函数。
C,若当前系统是Mac系统,则使用<malloc/malloc.h>中的内存分配函数。
D,其他情况,在每一段分配好的空间前头,同时多分配一个定长的字段,用来记录分配的空间大小。
差别(仅供参考)
使用Redis自带的redis-benchmark写入等量数据进行测试,数据摘自采用不同分配器时Redis info信息。我们可以看到,采用tcmalloc时碎片率是最低的,为1.01,jemalloc为1.02,而libc的分配器碎片率为1.31。
RSS
Resident Set Size,进程实际锁驻留在内存的空间大小,不包括交换区数据(swap)值。
PREFIX_SIZE
上述代码中的PREFIX_SIZE解释:由于malloc函数申请的内存不会标识内存块的大小,而我们需要统计内存大小,所以需要在多申请PREFIX_SIZE大小的内存,用于存放该大小。
源码概述

源码注释
zmalloc.h
/* zmalloc - total amount of allocated memory aware version of malloc() * redis的内存分配管理程序 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
#ifndef __ZMALLOC_H
#define __ZMALLOC_H
/* Double expansion needed for stringification of macro values. */
#define __xstr(s) __str(s)
#define __str(s) #s
//检查是否定义了TCMalloc,TCMalloc(Thread-Caching Malloc)与标准glibc库的malloc实现一样的功能,
// 但是TCMalloc在效率和速度效率都比标准malloc高很多
// HAVE_MALLOC_SIZE 标记已经找到了可用的现成函数库
#if defined(USE_TCMALLOC)
#define ZMALLOC_LIB ("tcmalloc-" __xstr(TC_VERSION_MAJOR) "." __xstr(TC_VERSION_MINOR))
#include <google/tcmalloc.h>
#if (TC_VERSION_MAJOR == 1 && TC_VERSION_MINOR >= 6) || (TC_VERSION_MAJOR > 1)
#define HAVE_MALLOC_SIZE 1
#define zmalloc_size(p) tc_malloc_size(p)
#else
#error "Newer version of tcmalloc required"
#endif
//检查是否定义了jemalloc库
#elif defined(USE_JEMALLOC)
#define ZMALLOC_LIB ("jemalloc-" __xstr(JEMALLOC_VERSION_MAJOR) "." __xstr(JEMALLOC_VERSION_MINOR) "." __xstr(JEMALLOC_VERSION_BUGFIX))
#include <jemalloc/jemalloc.h>
#if (JEMALLOC_VERSION_MAJOR == 2 && JEMALLOC_VERSION_MINOR >= 1) || (JEMALLOC_VERSION_MAJOR > 2)
#define HAVE_MALLOC_SIZE 1
#define zmalloc_size(p) je_malloc_usable_size(p)
#else
#error "Newer version of jemalloc required"
#endif
//检查是否是苹果系统
#elif defined(__APPLE__)
#include <malloc/malloc.h>
#define HAVE_MALLOC_SIZE 1
#define zmalloc_size(p) malloc_size(p)
#endif
#ifndef ZMALLOC_LIB
#define ZMALLOC_LIB "libc"
#endif
void *zmalloc(size_t size); //重写malloc函数,申请内存
void *zcalloc(size_t size); //重写calloc函数,不再支持按块的成倍申请,内部调用的是zmalloc
void *zrealloc(void *ptr, size_t size);//重写realloc函数
void zfree(void *ptr); //重写free函数 释放时会更新已使用内存的值,如果在多线程下没有开启线程安全模式,可能会出现并发错误。
char *zstrdup(const char *s);//生成一个字符串的拷贝 字符串持久化存储函数,为字符串在堆内分配内存。
size_t zmalloc_used_memory(void);//获取已经使用内存大小函数。
void zmalloc_enable_thread_safeness(void);//设置内存管理为多线程安全模式,设置之后在更新已使用内存大小时会用Mutex进行互斥操作。
void zmalloc_set_oom_handler(void (*oom_handler)(size_t));//设置内存异常时调用的函数。
float zmalloc_get_fragmentation_ratio(size_t rss); // 获取所给内存和已使用内存的大小之比
size_t zmalloc_get_rss(void); //获取进程可使用的所有内存大小。// 获取RSS信息(Resident Set Size)
size_t zmalloc_get_private_dirty(void); // 获得实际内存大小
void zlibc_free(void *ptr); //释放指针指向内存函数,用这个释放内存时,不会更新使用内存变量的值。
//HAVE_MALLOC_SIZE宏在config.h中定义
#ifndef HAVE_MALLOC_SIZE
size_t zmalloc_size(void *ptr); //获取内存块总体大小函数。
#endif
#endif /* __ZMALLOC_H */
zmalloc.c
/* zmalloc - total amount of allocated memory aware version of malloc() * * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
#include <stdio.h>
#include <stdlib.h>
/* This function provide us access to the original libc free(). This is useful * for instance to free results obtained by backtrace_symbols(). We need * to define this function before including zmalloc.h that may shadow the * free implementation if we use jemalloc or another non standard allocator. */
void zlibc_free(void *ptr) {
free(ptr);
}
#include <string.h>
#include <pthread.h>
#include "config.h"
#include "zmalloc.h"
/** * 确定内存块前面是否需要加个头部,因为不能确定具体使用的到底是什么内存分配函数, * TCMalloc或者Jemalloc库在申请的内存块前增加了一个小块的内存来记录该内存块的使用情况, 找到了已有的内存管理库时就会定义这个宏,如果已经定义了,则不再增加头部大小,如果没有定义,则根据具体的系统来确定增加头部大小的长度。 tc_malloc 、je_malloc 和 Mac平台下的 malloc 函数族提供了计算已分配空间大小的函数 (分别是tc_malloc_size, je_malloc_usable_size和malloc_size),所以就不需要单独分配一段空间记录大小了。 在linux和sun平台则要记录分配空间大小。对于linux,使用sizeof(size_t)定长字段记录; 对于sun 系统,使用sizeof(long long)定长字段记录,其对应源码中的 PREFIX_SIZE 宏。 */
#ifdef HAVE_MALLOC_SIZE
#define PREFIX_SIZE (0)
#else
#if defined(__sun) || defined(__sparc) || defined(__sparc__)
#define PREFIX_SIZE (sizeof(long long))
#else
#define PREFIX_SIZE (sizeof(size_t))
#endif
#endif
/* Explicitly override malloc/free etc when using tcmalloc. */
/*查看系统内是否安装了TCMalloc或者Jemalloc模块, * 这两个是已经存在很久的内存管理模块,代码稳定、性能优异, * 如果已经安装的话,则使用之*/
#if defined(USE_TCMALLOC)
#define malloc(size) tc_malloc(size)
#define calloc(count,size) tc_calloc(count,size)
#define realloc(ptr,size) tc_realloc(ptr,size)
#define free(ptr) tc_free(ptr)
#elif defined(USE_JEMALLOC)
#define malloc(size) je_malloc(size)
#define calloc(count,size) je_calloc(count,size)
#define realloc(ptr,size) je_realloc(ptr,size)
#define free(ptr) je_free(ptr)
#endif
/*先检查编译器是否支持原子操作函数,如果支持的话,就不用互斥锁了,毕竟锁的效率很低。 * 由于内存分配可能发生在各个线程中,所以对这个数据的管理要做到原子性。 * 但是不同平台原子性操作的方法不同,有的甚至不支持原子操作,这个时候Redis就要统一它们的行为 * */
#ifdef HAVE_ATOMIC
#define update_zmalloc_stat_add(__n) __sync_add_and_fetch(&used_memory, (__n))
#define update_zmalloc_stat_sub(__n) __sync_sub_and_fetch(&used_memory, (__n))
#else
// 如果上述都没有,则只能采用加锁操作
#define update_zmalloc_stat_add(__n) do {
\ pthread_mutex_lock(&used_memory_mutex); \ used_memory += (__n); \ pthread_mutex_unlock(&used_memory_mutex); \ } while(0)
#define update_zmalloc_stat_sub(__n) do {
\ pthread_mutex_lock(&used_memory_mutex); \ used_memory -= (__n); \ pthread_mutex_unlock(&used_memory_mutex); \ } while(0)
#endif
/* * 负责在分配内存或是释放内存的时候更新used_memory变量。update_zmalloc_stat_alloc定义如下: * * 用于在分配内存的时候更新已分配大小 if(将_n调整为sizeof(long)的整数倍) if(如果启用了线程安全模式){ 调用原子操作加(+)来更新已用内存 }else{ // 不考虑线程安全,则直接更新已用内存 } */
#define update_zmalloc_stat_alloc(__n) do {
\ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ if (zmalloc_thread_safe) {
\ update_zmalloc_stat_add(_n); \ } else {
\ used_memory += _n; \ } \ } while(0)
/* 1.用于在释放内存的时候删除对应的记录。 if(将内存大小调整为sizeof(long)的整数倍) if( 如果开启了线程安全模式){ // 更新use_memory值 }else{ 没有线程安全则直接减 } * */
#define update_zmalloc_stat_free(__n) do {
\ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ if (zmalloc_thread_safe) {
\ update_zmalloc_stat_sub(_n); \ } else {
\ used_memory -= _n; \ } \ } while(0)
/** * 记录了进程当前占用的内存总数。每当要分配内存或是释放内存的时候,都要更新这个变量(当然可以是线程安全的)。 * 因为分配内存的时候,需要指定分配多少内存。但是释放内存的时候, * (对于未提供malloc_size函数的内存库)通过指向要释放内存的指针是不能知道释放的空间到底有多大的。 * 这时候,上面提到的PREFIX_SIZE就起作用了,可以通过其中记录的内容得到空间的大小。 */
static size_t used_memory = 0; /*记录已经使用碓内存的大小*/
static int zmalloc_thread_safe = 0; /*是否开启了线程安全*/
pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER; /*互斥锁,如果开启了多线程安全,而编译器又不支持原子操作的函数,则需要用互斥锁来完成代码的互斥操作。*/
//异常处理函数
static void zmalloc_default_oom(size_t size) {
// 打印输出日志
fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n",
size);
fflush(stderr);
// 中断退出
abort();
}
static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom;
/** * 本质就是调用了系统的malloc函数,然后对其进行了适当的封装,加上了异常处理函数和内存统计 */
void *zmalloc(size_t size) {
// 调用malloc函数进行内存申请
// 多申请的PREFIX_SIZE大小的内存用于记录该段内存的大小
void *ptr = malloc(size+PREFIX_SIZE);
// 如果ptr为NULL,则调用异常处理函数
if (!ptr) zmalloc_oom_handler(size);
// 以下是内存统计
#ifdef HAVE_MALLOC_SIZE
update_zmalloc_stat_alloc(zmalloc_size(ptr));
return ptr;
#else
/** * 分配的内存前加一个固定大小的prefis-size空间,用于记录该段内存的大小,size所占据的内存大小是已知的, * 为size_t类型的长度,因此通过*((size_t*)ptr) = size; 即可对当前内存块大小进行指定。 * 每次分配内存后,返回的实际地址指针为指向memorysize的地址( (char*)ptr+PREFIX_SIZE; ), * 通过该指针,可以很容易的计算出实际内存的头地址,从而释放内存。 */
*((size_t*)ptr) = size;
update_zmalloc_stat_alloc(size+PREFIX_SIZE);// 更新used_memory的值
return (char*)ptr+PREFIX_SIZE;
#endif
}
/** * zcalloc调用的是系统给的calloc()来申请内存。 */
void *zcalloc(size_t size) {
void *ptr = calloc(1, size+PREFIX_SIZE);
// 异常处理函数
if (!ptr) zmalloc_oom_handler(size);
// 内存统计函数
#ifdef HAVE_MALLOC_SIZE
update_zmalloc_stat_alloc(zmalloc_size(ptr));
return ptr;
#else
*((size_t*)ptr) = size;
update_zmalloc_stat_alloc(size+PREFIX_SIZE);
return (char*)ptr+PREFIX_SIZE;
#endif
}
/** * 内存调整函数zrecalloc用于调整已申请内存的大小,其本质也是直接调用系统函数recalloc() * */
void *zrealloc(void *ptr, size_t size) {
#ifndef HAVE_MALLOC_SIZE
void *realptr;
#endif
size_t oldsize;
void *newptr;
// 为空直接退出
if (ptr == NULL) return zmalloc(size);
#ifdef HAVE_MALLOC_SIZE
oldsize = zmalloc_size(ptr);
newptr = realloc(ptr,size);
if (!newptr) zmalloc_oom_handler(size);
update_zmalloc_stat_free(oldsize);
update_zmalloc_stat_alloc(zmalloc_size(newptr));
return newptr;
#else
// 找到内存真正的起始位置
realptr = (char*)ptr-PREFIX_SIZE;
oldsize = *((size_t*)realptr);
// 调用recalloc函数
newptr = realloc(realptr,size+PREFIX_SIZE);
if (!newptr) zmalloc_oom_handler(size);
// 内存统计
*((size_t*)newptr) = size;
update_zmalloc_stat_free(oldsize); // 先减去原来的已使用内存大小
update_zmalloc_stat_alloc(size); // 在加上调整后的大小
return (char*)newptr+PREFIX_SIZE;
#endif
}
/* Provide zmalloc_size() for systems where this function is not provided by * malloc itself, given that in that case we store a header with this * information as the first bytes of every allocation. * 为 malloc 本身不提供此功能的系统提供 zmalloc_size() ,因为在这种情况下,我们将带有此信息的标头存储为每个分配的第一个字节。 * */
#ifndef HAVE_MALLOC_SIZE
size_t zmalloc_size(void *ptr) {
void *realptr = (char*)ptr-PREFIX_SIZE;
size_t size = *((size_t*)realptr);
/* Assume at least that all the allocations are padded at sizeof(long) by * the underlying allocator. */
if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1));
return size+PREFIX_SIZE;
}
#endif
/** * 内存释放函数 */
void zfree(void *ptr) {
#ifndef HAVE_MALLOC_SIZE
void *realptr;
size_t oldsize;
#endif
if (ptr == NULL) return;// 为空直接返回
#ifdef HAVE_MALLOC_SIZE
update_zmalloc_stat_free(zmalloc_size(ptr));
free(ptr);
#else
realptr = (char*)ptr-PREFIX_SIZE;// 找到该段内存真正的起始位置
oldsize = *((size_t*)realptr);
update_zmalloc_stat_free(oldsize+PREFIX_SIZE);// 更新use_memory函数
free(realptr);// 调用系统的内存释放函数
#endif
}
/** * 字符串复制方法 * @param s * @return */
char *zstrdup(const char *s) {
size_t l = strlen(s)+1;
char *p = zmalloc(l);// 开辟一段新内存
memcpy(p,s,l);// 调用字符串复制函数
return p;
}
/** * 获取已使用内存 * @return */
size_t zmalloc_used_memory(void) {
size_t um;
// 如果开启了线程安全模式
if (zmalloc_thread_safe) {
#ifdef HAVE_ATOMIC
um = __sync_add_and_fetch(&used_memory, 0);
#else
pthread_mutex_lock(&used_memory_mutex);
um = used_memory;
pthread_mutex_unlock(&used_memory_mutex);
#endif
}
else {
um = used_memory;// 未开启则直接使用used_memory
}
return um;
}
/** * 开启线程安全 */
void zmalloc_enable_thread_safeness(void) {
zmalloc_thread_safe = 1; // 此参数用来控制是否开启线程安全
}
/** * 设置异常处理函数 * @param oom_handler * * * */
void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) {
zmalloc_oom_handler = oom_handler;// 绑定自定义的异常处理函数
}
/* Get the RSS information in an OS-specific way. * 以特定于操作系统的方式获取 RSS 信息 * WARNING: the function zmalloc_get_rss() is not designed to be fast * and may not be called in the busy loops where Redis tries to release * memory expiring or swapping out objects. * 警告:函数 zmalloc_get_rss() 的设计速度不快,可能不会在 Redis 尝试释放内存到期或换出对象的繁忙循环中调用。 * For this kind of "fast RSS reporting" usages use instead the * function RedisEstimateRSS() that is a much faster (and less precise) * version of the function. * 对于这种“快速 RSS 报告”的用法,请改用函数 RedisEstimateRSS(),它是该函数的一个更快(且精度更低)的版本。 * * 获取RSS的大小,是指的Resident Set Size,表示当前进程实际所驻留在内存中的空间大小,即不包括被交换(swap)出去的空间。 了解一点操作系统的知识,就会知道我们所申请的内存空间不会全部常驻内存, 系统会把其中一部分暂时不用的部分从内存中置换到swap区(装Linux系统的时候我们都知道有一个交换空间)。 如果你使用过top命令,就知道进程状态有两列指标:RSS和SWAP 该函数大致的操作就是在当前进程的 /proc/<pid>/stat (<pid>指代当前进程实际id)文件中进行检索。 该文件的第24个字段是RSS的信息,它的单位是pages(内存页的数目) https://zhuanlan.zhihu.com/p/60925899 * */
#if defined(HAVE_PROC_STAT)
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
size_t zmalloc_get_rss(void) {
int page = sysconf(_SC_PAGESIZE);
size_t rss;
char buf[4096];
char filename[256];
int fd, count;
char *p, *x;
snprintf(filename,256,"/proc/%d/stat",getpid());
if ((fd = open(filename,O_RDONLY)) == -1) return 0;
if (read(fd,buf,4096) <= 0) {
close(fd);
return 0;
}
close(fd);
p = buf;
count = 23; /* RSS is the 24th field in /proc/<pid>/stat */
while(p && count--) {
p = strchr(p,' ');
if (p) p++;
}
if (!p) return 0;
x = strchr(p,' ');
if (!x) return 0;
*x = '\0';
rss = strtoll(p,NULL,10);
rss *= page;
return rss;
}
#elif defined(HAVE_TASKINFO)
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <mach/task.h>
#include <mach/mach_init.h>
size_t zmalloc_get_rss(void) {
task_t task = MACH_PORT_NULL;
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (task_for_pid(current_task(), getpid(), &task) != KERN_SUCCESS)
return 0;
task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
return t_info.resident_size;
}
#else
/** * 这个函数用来获取进程的RSS。神马是RSS?全称为Resident Set Size,指实际使用物理内存(包含共享库占用的内存)。 * 在linux系统中,可以通过读取/proc/pid/stat文件系统获取,pid为当前进程的进程号。 * 读取到的不是byte数,而是内存页数。通过系统调用sysconf(_SC_PAGESIZE)可以获得当前系统的内存页大小。 * 获得进程的RSS后,可以计算目前数据的内存碎片大小,直接用rss除以used_memory。rss包含进程的所有内存使用,包括代码,共享库,堆栈等。 * 哪来的内存碎片?上面我们已经说明了通常考虑到效率,往往有内存对齐等方面的考虑,所以,碎片就在这里产生了。 * 相比传统glibc中的malloc的内存利用率不是很高一般会使用别的内存库系统。 * 在redis中默认的已经不使用简单的malloc了而是使用 jemalloc, 在源文件src/Makefile下有这样一段代码: * * 获取RSS的大小,是指的Resident Set Size,表示当前进程实际所驻留在内存中的空间大小,即不包括被交换(swap)出去的空间。 了解一点操作系统的知识,就会知道我们所申请的内存空间不会全部常驻内存, 系统会把其中一部分暂时不用的部分从内存中置换到swap区(装Linux系统的时候我们都知道有一个交换空间)。 如果你使用过top命令,就知道进程状态有两列指标:RSS和SWAP 该函数大致的操作就是在当前进程的 /proc/<pid>/stat (<pid>指代当前进程实际id)文件中进行检索。 该文件的第24个字段是RSS的信息,它的单位是pages(内存页的数目) */
size_t zmalloc_get_rss(void) {
/* If we can't get the RSS in an OS-specific way for this system just * return the memory usage we estimated in zmalloc().. * * Fragmentation will appear to be always 1 (no fragmentation) * of course... */
return zmalloc_used_memory();
}
#endif
/* Fragmentation = RSS / allocated-bytes */
float zmalloc_get_fragmentation_ratio(size_t rss) {
return (float)rss/zmalloc_used_memory();
}
#if defined(HAVE_PROC_SMAPS)
size_t zmalloc_get_private_dirty(void) {
char line[1024];
size_t pd = 0;
FILE *fp = fopen("/proc/self/smaps","r");
if (!fp) return 0;
while(fgets(line,sizeof(line),fp) != NULL) {
if (strncmp(line,"Private_Dirty:",14) == 0) {
char *p = strchr(line,'k');
if (p) {
*p = '\0';
pd += strtol(line+14,NULL,10) * 1024;
}
}
}
fclose(fp);
return pd;
}
#else
size_t zmalloc_get_private_dirty(void) {
return 0;
}
#endif
边栏推荐
- iis怎么打开md文件(is无法打开md文件报错怎么解决)
- Epigentek chromatin accessibility test kit principles and procedures
- Android caching mechanism lrucache
- Gesture interaction across the space, performing "handy" in the real world
- Android 缓存机制 LRUCache
- UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xad in position 2: illegal multibyte sequence
- Epigentek hi fi cDNA synthesis kit instructions
- Vulkan规范笔记(一) 第一章至第六章
- Word tips
- AI首席架构师3-AICA-智慧城市中的AI应用实践
猜你喜欢

Gesture interaction across the space, performing "handy" in the real world

What is the expected life of the conductive slip ring

隔空手势交互,在现实世界上演“得心应手”
![【长时间序列预测】Aotoformer 代码详解之[1]数据预处理及数据读取](/img/65/a3629909b1e9962416f23c9a07bf24.png)
【长时间序列预测】Aotoformer 代码详解之[1]数据预处理及数据读取

word论文格式

UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xad in position 2: illegal multibyte sequence

Imshow() of OpenCV to view the pixel value of the picture

关于并发和并行,Go和Erlang之父都弄错了?
MySQL 8.0.29 解压版安装配置方法图文教程

Epigentek Hi-Fi cDNA 合成试剂盒说明书
随机推荐
阿里10年技术人:Leader的7种思考方式
Android caching mechanism lrucache
DAY6-T1345&T39 -2022-01-21-非自己作答
How about opening an account with tongdaxin? Is it safe to open an account?
I/o flow
充电桩的B面是......不只公众号?还有智充小程序!
[long time series prediction] detailed explanation of aotoformer code [1] data preprocessing and data reading
君可归烈士寻亲系统开发实战
sqllite create a database
音频 3A 处理实践,让你的应用更「动听」
Vulkan規範筆記(一) 第一章至第六章
Redis knowledge points & summary of interview questions
NLP- 关键词提取 - 综述
pta7-6悄悄关注
CNN - nn. Conv1d use
导电滑环的预期寿命是什么
演练-分组和聚合函数的组合使用
Mediapipe body and hand key points
C language to solve the problem of climbing stairs
IIS how to open the MD file (how to solve the error when is cannot open the MD file)