返回介绍

2. 内存管理

发布于 2024-10-12 21:58:09 字数 3157 浏览 0 评论 0 收藏 0

相比 glibc ptmalloc,Google tcmalloc 和 Facebook jemalloc 对高并发长时间运行的后台服务效率更高。

$ apt install -y libjemalloc-dev

使用方式:

  • 无需修改源码,直接 -ljemalloc 链接即可。
  • 已有程序,用 LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so 启动。
$ gcc -g -O0 -o test main.c -ljemalloc   # 链接参数放输入文件后面。
$ MALLOC_CONF=stats_print:true ./test    # 检查 jemalloc 是否启用。

垃圾回收

虽然有点另类,但的确有个发展了很多年的 C/C++ 垃圾回收器。

The Boehm-Demers-Weiser conservative garbage collector can be used as a garbage collecting replacement for C malloc or C++ new. It allows you to allocate memory basically as you normally would, without explicitly deallocating memory that is no longer useful. The collector automatically recycles memory when it determines that it can no longer be otherwise accessed.

$ apt install -y libgc-dev
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <gc/gc.h>

void test () 
{
    char *s = GC_MALLOC(1<<20);  // 1 MB
    // char *s = malloc(1<<20);
    *s = 0x10; 
}

int main (void)
{
    for (int i = 0; i < 100; i++) {
        printf("%d, heap = %ld\n", i, GC_get_heap_size());
        test();
        sleep(1);
    }

    // getchar();
    return 0; 
}
$ gcc -o test test.c -lgc

安全检查

利用 Valgrind 检查内存安全问题,诸如:内存泄漏(memory leak),使用未初始化变量(uninitialized)等。

$ apt install -y valgrind
$ valgrind --leak-check=full --show-reachable=yes --log-file=mem.log ./test

还可利用 cachegrind 检查 CPU 缓存命中情况。

I1 : L1 指令; D1 : L1 数据; LL : 最后一级缓存。

rd : 读; wr : 写。

$ valgrind --tool=cachegrind ./test

==3369== Cachegrind, a cache and branch-prediction profiler
==3369== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==3369== Command: ./test
==3369== 
--3369-- warning: L3 cache found, using its data for the LL simulation.
0
==3369== 
==3369== I   refs:      179,941
==3369== I1  misses:      1,113
==3369== LLi misses:      1,091
==3369== I1  miss rate:    0.62%
==3369== LLi miss rate:    0.61%
==3369== 
==3369== D   refs:       53,145  (41,400 rd   + 11,745 wr)
==3369== D1  misses:      3,181  ( 2,509 rd   +    672 wr)
==3369== LLd misses:      2,635  ( 2,035 rd   +    600 wr)
==3369== D1  miss rate:     6.0% (   6.1%     +    5.7%  )
==3369== LLd miss rate:     5.0% (   4.9%     +    5.1%  )
==3369== 
==3369== LL refs:         4,294  ( 3,622 rd   +    672 wr)
==3369== LL misses:       3,726  ( 3,126 rd   +    600 wr)
==3369== LL miss rate:      1.6% (   1.4%     +    5.1%  )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文