内存泄漏和用户体验不佳

发布于 2024-10-27 11:33:38 字数 764 浏览 0 评论 0原文

我的一个应用程序中出现了严重的内存泄漏:每当泄漏发生时,我的计算机就会变得非常慢。在修复泄漏之前,我想了解为什么会发生这种情况。

举个例子,下面有一个泄漏的小 C++ 代码:

size_t size = 1024 * 1024 * 1024;
char* buf = new char[size];
std::fill_n(buf, size, 'o');
std::string pause;
std::getline(std::cin, pause);

根据我对虚拟内存、磁盘缓存等的理解,我预计当上面的代码在最后一行等待用户输入时,它的 1 GB 缓冲区是不再使用,因此操作系统应该逐渐将其交换到磁盘并“忘记”它。我(用户)会在一段时间内遭遇速度减慢的情况,但一段时间后一切都会恢复正常。

我的系统(Windows XP,32 位,2 GB RAM)上不会发生这种情况。当我运行上面的代码时(两次,在两个单独的 cmd 窗口中,以浪费所有可用内存),我感觉系统速度大大减慢;几分钟后它会变得更好,但还没有接近最大性能。在我终止泄漏的“应用程序”后,系统恢复正常。

为了显示一些数字,我使用了一些源代码的编译作为性能测试。我连续编译了几次以进行多次测量(以秒为单位)。

  • 泄漏前: 14, 2, 2, 3, 2, ...
  • 泄漏后: 183, 40, 9, 7, 9, ...
  • 关闭泄漏“应用程序”后: 12, 2, 2, .. 减速了 3 倍,

而我预计不会。这该如何解释呢?

I have been suffering from a massive memory leak in one of my applications: my computer would go very slow whenever the leak happened. Before i fix the leak, i would like to understand why that happens.

Take, for example, the following small C++ code with a leak:

size_t size = 1024 * 1024 * 1024;
char* buf = new char[size];
std::fill_n(buf, size, 'o');
std::string pause;
std::getline(std::cin, pause);

From my understanding of virtual memory, disk caches, etc., i would expect that while the above code waits for user input at the last line, its 1-gigabyte buffer is not being used anymore, so the operating system should gradually swap it to disk and "forget" it. I (the user) would suffer a slowdown for some time, but things would return to normal after some time.

This is not what happens on my system (Windows XP, 32-bit, with 2 GB of RAM). When i run the above code (twice, in 2 separate cmd windows, in order to waste all available memory), i feel a great slowdown of my system; it gets better after a few minutes but doesn't get close to maximal performance. The system returns to normal after i terminate the leaking "applications".

Just to show some numbers, i used compilation of some source code as a performance test. I compiled it several times in a row to make several measurements (in seconds).

  • Before the leak: 14, 2, 2, 3, 2, ...
  • After the leak: 183, 40, 9, 7, 9, ...
  • After closing the leaking "applications": 12, 2, 2, ...

A slowdown of 3x where i would expect none. How can this be explained?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤独患者 2024-11-03 11:33:38

Windows 交换文件的大小是有限的。如果您用 1GB 缓冲区填满了大部分内存,那么系统必须更加努力地工作,将剩余的内存换入或换出剩余的内存。

The Windows swap file is of finite size. If you fill most of it up with your 1GB buffer, then the system has to work harder, swapping the rest of memory in and out of what little remains.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文