Private bytes что это
Перейти к содержимому

Private bytes что это

  • автор:

Process Explorer. Обзор некоторых возможностей

Process Explorer – альтернатива стандартному Task Manager-у. Эта утилита, как и многие другие утилиты Sysinternals, здорово расширяет возможности контроля и управления системой. Главное новшество только что вышедшей 14-ой версии — возможность мониторить сетевую активность процессов. Далее небольшой обзор возможностей этой утилиты, которые считаю наиболее полезными для себя.

Для справки. С 2006 года Sysinternals была приобретена Microsoft, а ключевая фигура этой компании – Марк Руссинович с тех пор работает в Microsoft. Марк известен своими утилитами, книгой Windows Internals, блогом и является признанным специалистом по архитектуре Windows.

  • Колонки в главном окне
  • Сервисы внутри svchost
  • Суммарные графики активности, процесс с максимальной активностью
  • Суммарные графики активности в трее, процесс с максимальной активностью
  • Сетевые соединения процесса
  • Потоки процесса, их активность, стек потока с загрузкой символов
  • Информация по использованию памяти в системе
  • Handles и DLL процесса
  • Поиск handles и DLL

Колонки в главном окне

1

2

  1. Имя процесса
  2. Владелец процесса, я использую сортировку по этому полю, чтобы первыми шли пользовательские процессы, потом системные
  3. Загрузка CPU процессом
  4. Суммарное затраченное время CPU, интересно иногда обращать на это внимание, полезен для таймирования
  5. Private bytes — объем занимаемой процессом памяти (реально выделенные страницы, исключая shared)
  6. Peak private bytes — пиковое значение Private bytes, интересно иногда взглянуть до чего дело доходило
  7. I/O read bytes — суммарный объем считанных с диска данных, по изменению видна активность
  8. I/O write bytes — суммарный объем записанных на диск данных, по изменению видна активность
  9. Network receive bytes — суммарный объем считанных из сети данных, по изменению видна активность
  10. Network send bytes — суммарный объем переданных в сеть данных, по изменению видна активность
  11. Описание процесса
  12. Название компании
  13. Полный путь к образу процесса (тут можно точно понять откуда стартовал процесс)
  14. Командная строка запуска процесса

Сервисы внутри svchost

При наведении курсора на svchost (процесс который хостит в себе сервисы) можно видеть перечень сервисов – довольно полезная фича.

ScreenShot00243

Суммарные графики активности, процесс с максимальной активностью

Сверху основного окна расположены графики основных суммарных параметров – память, дисковая, сетевая и CPU активность. При перемещении курсора по истории параметра, показан процесс который дал максимальный вклад в это значение в данный момент времени. Кроме того в тултипе есть информация о мгновенном значении параметра (зависит от частоты обновления). На следующей картинке — график сетевой активности.

ScreenShot00239

В окне «system information» графики собраны вместе, здесь удобнее смотреть корреляцию параметров.

ScreenShot00262

Суммарные графики активности в трее, процесс с максимальной активностью

Очень удобная фича – выведение в трей иконок с графиками суммарной активности. Там могут быть графики дисковой активности, CPU и память. Я использую первые два – поглядываю туда, при возникновении вопросов достаточно навести курсор и узнать какой процесс дает максимальный вклад в параметр. К сожалению сетевую активность туда нельзя выставить, я надеюсь это вопрос времени.

ScreenShot00240ScreenShot00241

Сетевые соединения процесса

В свойствах процесса в закладке TCP/IP можно посмотреть текущие активные соединения. К сожалению сетевая активность по ним не видна, эта функциональность пока доступна в другой утилите – tcpview.

ScreenShot00254

Потоки процесса, их активность, стек потока с загрузкой символов

В свойствах процесса в закладке threads видны все его потоки и загрузка CPU по потокам. Допустим хочется рассмотреть стек потока, который интенсивно что-то делает или висит. Для этого сперва надо его распознать, допустим по загрузке CPU, потом полезно приостановить процесс, чтобы спокойно рассмотреть его состояние — это можно сделать прямо в этом окне по кнопке “suspend”. Далее выделяем поток и нажимаем “stack”. В большинстве случаев стек будет начинаться в недрах системы и обрываться не совсем понятным образом. Дело в том, что не имея отладочной информации по системным библиотекам не удастся корректно развернуть стек и разобраться в нем. Есть решение – нужно сконфигурировать доступ с символьной информации с сайта Microsoft. Надо проделать несколько шагов:

  1. Установить Debugging Tools. Из приведенной ссылки надо пойти по ссылке “Debugging Tools for Windows 32-bit Versions” или “Debugging Tools for Windows 64-bit Versions”. Далее выбрать для скачивания последнюю версию не интегрированную в SDK, иначе это выльется в скачивание огромного объема SDK, а так всего несколько Mb.
  2. Настроить доступ к символам в Process Explorer. Options –> Configure Symbols. В одном поле задаем путь к dbghelp.dll, которая находится внутри установленного продукта из шага 1. Во втором настраиваем такую хитрую строку: “srv*C:\Symbols*http://msdl.microsoft.com/download/symbols”. Часть строки указывает на локальный кэш для PDB файлов, вторая часть на путь к серверу для скачивания.
  3. Теперь список потоков и стек будут более информативны. При открытии этих окон может происходить задержка на время подкачки PDB файлов с сервера Microsoft, но делается это один раз для каждой версии модуля, результат кэшируется в выбранной папке.

ScreenShot00256

Информация по использованию памяти в системе

В окне «system information» закладка «memory». Здесь есть два графика – commit и physical. Physical – использование физической памяти без учета файлового кэша, под который уходит все что остается. Commit – сколько памяти выделено для процессов включая используемую виртуальную память. Под графиками в разделе «Commit Charge» есть поля Limit и Peak. Limit определяется суммой физической и виртуальной памяти, т.е. это максимальный суммарный объем памяти, который может выделить система. Peak – это максимум графика Commit за время работы утилиты. Процентные соотношения Current/Limit и Peak/Limit удобны для быстрой оценки насколько состояние системы приближалось к критическому лимиту по доступной памяти.

ScreenShot00257

Handles и DLL процесса

В главном окне можно включить разделитель и снизу отображать DLL или handles выделенного процесса. При борьбе с вирусами и отладке программ это бывает очень полезно. На картинке — список handles для opera, первый handle файловой системы – это flash ролик в временном каталоге.

ScreenShot00258

Для DLL можно добавить колонку с полным путем к образу, отсортировав по нему, проанализировать нет ли каких подозрительных модулей. На картинке видно, что подключен модуль от Logitech, есть подозрение что это что-то типа хука внедряющегося во все процессы. Следующим пунктом посмотрим где он еще встречается.

ScreenShot00259

Поиск handles и DLL

Поиск по имени handle или DLL во всех процессах. Вводим имя DLL от Logitech из предыдущего пункта и убеждаемся что подключается он почти везде.

ScreenShot00260

Другой пример – надо понять, кто блокирует файл или работает с папкой. Вводим часть пути и находим все процессы, которые открыли подобные объекты системы. Можно щелкнуть на элементе из списка и перейти к процессу, при этом будет подсвечен соответствующий handle или DLL.

ScreenShot00261

PS Для отображения некоторых полей (например сетевая статистика) требуются административные привилегии. Повысить привилегии в уже запущенном Process Explorer можно с помощью команды в меню File. Только при наличии таких привилегий есть возможность добавить такие колонки. Я считаю такое поведение неверным, т.к. скрывает потенциальные возможности приложения от пользователя. Если поля добавлены и при следующем запуске нет административных прав, то они будут пустыми. Можно задать ключ «/e» в командной строке, чтобы форсировать поднятие привилегий при старте Process Explorer.

What is private bytes, virtual bytes, working set?

I am trying to use the perfmon windows utility to debug memory leaks in a process.

This is how perfmon explains the terms:

Working Set is the current size, in bytes, of the Working Set of this process. The Working Set is the set of memory pages touched recently by the threads in the process. If free memory in the computer is above a threshold, pages are left in the Working Set of a process even if they are not in use. When free memory falls below a threshold, pages are trimmed from Working Sets. If they are needed they will then be soft-faulted back into the Working Set before leaving main memory.

Virtual Bytes is the current size, in bytes, of the virtual address space the process is using. Use of virtual address space does not necessarily imply corresponding use of either disk or main memory pages. Virtual space is finite, and the process can limit its ability to load libraries.

Private Bytes is the current size, in bytes, of memory that this process has allocated that cannot be shared with other processes.

These are the questions I have:

Is it the Private Bytes which I should measure to be sure if the process is having any leaks as it does not involve any shared libraries and any leaks, if happening, will come from the process itself?

What is the total memory consumed by the process? Is it the Virtual Bytes or is it the sum of Virtual Bytes and Working Set?

Is there any relation between Private Bytes, Working Set and Virtual Bytes?

Are there any other tools that give a better idea of the memory usage?

4 Answers 4

The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.

Private Bytes refer to the amount of memory that the process executable has asked for — not necessarily the amount it is actually using. They are «private» because they (usually) exclude memory-mapped files (i.e. shared DLLs). But — here’s the catch — they don’t necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).

Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it’s an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager’s «Mem Usage» and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is «physical» in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the «Mem Usage» suddenly drop when you minimize an application.

Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.

So the relationships are:

  • Private Bytes are what your app has actually allocated, but include pagefile usage;
  • Working Set is the non-paged Private Bytes plus memory-mapped files;
  • Virtual Bytes are the Working Set plus paged Private Bytes and standby list.

There’s another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app’s Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it’s actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.

Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.

One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.

I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.

Private Bytes, Virtual Bytes, and Working Set

In this tutorial, we’ll discuss three memory-related concepts in the operating system: private bytes, virtual bytes, and working sets.

Finally, we’ll discuss the core differences between them.

2. Private Bytes

Private bytes are the reasonable approximation of the amount of memory an application requests during or before execution. Specifically, when a process completely exhausts its private memory, private bytes indicate the amount of RAM allocated to a process by the operating system. However, an important aspect of the private byte set is that it always indicates the memory allocated, not the memory used by the process.

A process utilizes the private byte set in order to request RAM from the OS. Although, the process may or may not use the whole allocated memory. We don’t include memory-mapped files in the private bytes set. It can consist of physical as well as disk memory.

We can use a private byte set to monitor and analyze any continuous increase in private memory. For instance, an allocation request in an unwanted infinite loop of an application may lead to a memory leak in the system. We can identify a memory leak by monitoring the continuous increase in the application’s private byte set.

In a private byte set, processes don’t share the requested memory with other processes. Additionally, processes don’t use the whole requested memory during execution. Moreover, a process’s private bytes include its pagefile usage. A pagefile is a reserved portion of hard disk memory that the OS has not used for a long time.

Therefore, the actual allocated memory of the private set is the sum of the memory used for the private byte set and pagefile memory:

rytrhytr.drawio-1

3. Working Set

During the execution of an application, we can view the working byte set as the pages of a process currently present in physical memory. A working set contains the most recent pages in RAM that have been allocated by a specific process.

However, if a process requests a page that has not previously been loaded in physical memory, an error occurs. The error leads to a page fault in the system. Additionally, we can explore the missing pages using the page fault handler. Nevertheless, after finding the missing page, we can include it in the working set. Therefore, in such a case, the total size of the working set will be increased by the amount of the newly added page’s size. We can divide page faults into two categories: hard and soft page faults.

We can resolve hard page faults by reading the paging file or memory-mapped file created by the process that requested the faulty page. The system reads the content of the backing store files to retrieve the desired page’s content. After the retrieval, we add the page to the working set.

Soft page faults don’t require reading backline store files. It can occur in a variety of situations. Let’s discuss some of them. Let’s assume a page is being executed within another working set of another process. In such a case, soft page fault can occur. Additionally, a page that is in transition after leaving a working set of a process can also lead to soft page fault.

If a process is completed using one of the working set pages, the page will be removed from the set without affecting the remaining processes. If a page is not a part of any working set, it’s referred to as a transition page until it is requested or modified for another purpose.

Unlike the private byte set, the working set can include both non-paged private bytes as well as memory-mapped files.

4. Virtual Bytes

Virtual byte set refers to the virtual memory address space allotted to a process. It facilitates the freedom of usage where a unique process accesses every space of addresses. The virtual addresses don’t represent the current physical memory position. However, every process is accompanied by a page table that helps in the translation of virtual addresses into their corresponding physical addresses. When a process requests an address, the system responds with a physical address based on the page table.

We can extend the physical RAM using secondary storage and virtual spacing. This virtual memory exceeds the capacity of RAM to get more address spacing and referencing addresses than the actual real memory. Let’s take an example. In 32-bit Windows user mode, a process can use a maximum of 2GB. However, we can expand the allocated memory to 3GB by modifying the Boot.ini file.

Virtual byte sets can include non-paged private bytes, memory-mapped files, and the data on a disk. Finally, the virtual byte set is a combination of the working set, private bytes, and a standby list:

rytrhytr.drawio-1

5. Differences

We can define the virtual byte set as the sum of the working set and private bytes. Additionally, the private bytes set is the sum of allocated memory and page usage memory of a process. Therefore, the private byte set is the superset of the working set. Furthermore, the virtual byte set is the superset of private byte and working sets:

sets

Now let’s take a look at the comparisons between the three sets:

6. Conclusion

In this tutorial, we explored some memory-related concepts in the operating system: private bytes, virtual bytes, and working sets.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *