Process. Working Set64 Свойство
Определение
Получает объем физической памяти в байтах, выделенной для связанного процесса. Gets the amount of physical memory, in bytes, allocated for the associated process.
Значение свойства
Объем физической памяти в байтах, выделенной для связанного процесса. The amount of physical memory, in bytes, allocated for the associated process.
Примеры
В следующем примере кода запускается экземпляр приложения Notepad. The following code example starts an instance of the Notepad application. Затем в примере извлекаются и отображаются различные свойства связанного процесса. The example then retrieves and displays various properties of the associated process. В примере обнаруживается, когда процесс завершается, и отображается его код выхода и Пиковая статистика памяти. The example detects when the process exits, and displays its exit code and peak memory statistics.
Комментарии
Значение, возвращаемое этим свойством, представляет самый последний обновленный размер памяти рабочего набора, используемый процессом, в байтах. The value returned by this property represents the most recently refreshed size of working set memory used by the process, in bytes. Чтобы получить наиболее актуальный размер, сначала необходимо вызвать Refresh() метод. To get the most up to date size, you need to call Refresh() method first.
Рабочий набор процесса — это набор страниц памяти, которые в настоящее время видны процессу в физической ОПЕРАТИВной памяти. The working set of a process is the set of memory pages currently visible to the process in physical RAM memory. Эти страницы являются резидентными и доступны для использования приложением без активации ошибки страницы. These pages are resident and available for an application to use without triggering a page fault.
Рабочий набор включает как общие, так и частные данные. The working set includes both shared and private data. Общие данные включают страницы, содержащие все инструкции, выполняемые процессом, включая инструкции в модулях процессов и системных библиотеках. The shared data includes the pages that contain all the instructions that the process executes, including instructions in the process modules and the system libraries.
Это свойство можно использовать для наблюдения за использованием памяти на компьютерах с 32-разрядными процессорами или 64-разрядными процессорами. This property can be used to monitor memory usage on computers with 32-bit processors or 64-bit processors. Значение свойства эквивалентно значению счетчика производительности » Рабочий набор » для процесса. The property value is equivalent to the Working Set performance counter for the process.
Working Set
The working set of a process is the set of pages in the virtual address space of the process that are currently resident in physical memory. The working set contains only pageable memory allocations; nonpageable memory allocations such as Address Windowing Extensions (AWE) or large page allocations are not included in the working set.
When a process references pageable memory that is not currently in its working set, a page fault occurs. The system page fault handler attempts to resolve the page fault and, if it succeeds, the page is added to the working set. (Accessing AWE or large page allocations never causes a page fault, because these allocations are not pageable .)
A hard page fault must be resolved by reading page contents from the page’s backing store, which is either the system paging file or a memory-mapped file created by the process. A soft page fault can be resolved without accessing the backing store. A soft page fault occurs when:
- The page is in the working set of some other process, so it is already resident in memory.
- The page is in transition, because it either has been removed from the working sets of all processes that were using the page and has not yet been repurposed, or it is already resident as a result of a memory manager prefetch operation.
- A process references an allocated virtual page for the first time (sometimes called a demand-zero fault).
Pages can be removed from a process working set as a result of the following actions:
- The process reduces or empties the working set by calling the SetProcessWorkingSetSize, SetProcessWorkingSetSizeEx or EmptyWorkingSet function.
- The process calls the VirtualUnlock function on a memory range that is not locked.
- The process unmaps a mapped view of a file using the UnmapViewOfFile function.
- The memory manager trims pages from the working set to create more available memory.
- The memory manager must remove a page from the working set to make room for a new page (for example, because the working set is at its maximum size).
If several processes share a page, removing the page from the working set of one process does not affect other processes. After a page is removed from the working sets of all processes that were using it, the page becomes a transition page. Transition pages remain cached in RAM until the page is either referenced again by some process or repurposed (for example, filled with zeros and given to another process). If a transition page has been modified since it was last written to disk (that is, if the page is «dirty»), then the page must be written to its backing store before it can be repurposed. The system may start writing dirty transition pages to their backing store as soon as such pages become available.
Each process has a minimum and maximum working set size that affect the virtual memory paging behavior of the process. To obtain the current size of the working set of a specified process, use the GetProcessMemoryInfo function. To obtain or change the minimum and maximum working set sizes, use the GetProcessWorkingSetSizeEx and SetProcessWorkingSetSizeEx functions.
The process status application programming interface (PSAPI) provides a number of functions that return detailed information about the working set of a process. For details, see Working Set Information.
Help understanding Windows memory — “Working Set”
I’ve been tracking down a few memory leaks in my application. It’s been a real pain, but I’ve finally tightened everything up. However, there’s one bit of Windows memory management that is confusing me. Here is a printout of the app’s memory usage over time.
The working set jumped from 49 MB to 146 over a span of 30 seconds. This happened overnight as the application was basically doing nothing.
The working set (which is what task manager shows me) seems to be able to be influenced by other applications such as debuggers (as I learned while looking for memory leaks). After reading the documentation on what Working Set is, I still don’t have a good understanding.
Any help is appreciated.
Update: Thanks to some links from responders as well as some additional searching, I have a better understanding on how a separate process can cause my process’ working set to grow. Good to know that a spike in the working set is not necessarily an indication that your app is leaking. Further reason to not rely on Task Manager for memory evaluation 🙂
2 Answers 2
Simply said, the working set is the collection of memory pages currently owned by your process and not swapped out (i.e. in RAM). That is somewhat inaccurate, however. Reality is a lot more complicated.
Windows maintains a minimum working set size and a maximum working set size for every process. The minimum working set is easy, it is what Windows will grant to every process (as long as it can, by physical limits).
The maximum working set is more dubious. If your program uses more memory than will fit in its quota, Windows will drop some pages. However, while they are no longer in your working set, these pages are not necessarily «gone».
Rather, those pages are removed from your working set and moved to the pool of available pages. As a consequence, if some other program needs more memory and no cleared pages are left over, your pages will be cleared, and assigned to a different process. When you access them, they will need to be fetched from the swapfile again, possibly purging other pages, if you are still above the maximum working set size.
However, if nobody asked for more memory in the mean time (or if all demands could be satisfied by pages that were unused anyway), then accessing one of those pages will simply make it «magically reappear» and kick out another page in its stead.
Thus, your process can have more pages in RAM than are actually in its working set, but it does not «officially» own them.
Process. Working Set Свойство
Определение
This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202
This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202
Возвращает использование физической памяти связанного процесса (в байтах). Gets the associated process’s physical memory usage, in bytes.
Значение свойства
Полное количество физической памяти в байтах, которое использует связанный процесс. The total amount of physical memory the associated process is using, in bytes.
Примеры
В следующем примере запускается экземпляр блокнота. The following example starts an instance of Notepad. Затем в примере извлекаются и отображаются различные свойства связанного процесса. The example then retrieves and displays various properties of the associated process. В примере обнаруживается, когда процесс завершается, и отображается код выхода процесса. The example detects when the process exits, and displays the process’ exit code.
Комментарии
Значение, возвращаемое этим свойством, представляет самый последний обновленный размер памяти рабочего набора, используемый процессом, в байтах. The value returned by this property represents the most recently refreshed size of working set memory used by the process, in bytes. Чтобы получить наиболее актуальный размер, сначала необходимо вызвать Refresh() метод. To get the most up to date size, you need to call Refresh() method first.
Рабочий набор процесса — это набор страниц памяти, которые в настоящее время видны процессу в физической ОПЕРАТИВной памяти. The working set of a process is the set of memory pages currently visible to the process in physical RAM memory. Эти страницы являются резидентными и доступны для использования приложением без активации ошибки страницы. These pages are resident and available for an application to use without triggering a page fault.
Рабочий набор включает как общие, так и частные данные. The working set includes both shared and private data. Общие данные включают страницы, содержащие все инструкции, выполняемые процессом, включая модули процессов и системные библиотеки. The shared data includes the pages that contain all the instructions that the process executes, including the process modules and the system libraries.
Set Windows process (or user) memory limit
Is there any way to set a system wide memory limit a process can use in Windows XP? I have a couple of unstable apps which do work ok for most of the time but can hit a bug which results in eating whole memory in a matter of seconds (or at least I suppose that’s it). This results in a hard reset as Windows becomes totally unresponsive and I lose my work.
I would like to be able to do something like the /etc/limits on Linux — setting M90, for instance (to set 90% max memory for a single user to allocate). So the system gets the remaining 10% no matter what.
4 Answers 4
Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.
In my case I need to simulate memory no longer being available so I did the following in the tool:
- Added my application
- Unchecked Basic
- Checked Low Resource Simulation
- Changed TimeOut to 120000 — my application will run normally for 2 minutes before anything goes into effect.
- Changed HeapAlloc to 100 — 100% chance of heap allocation error
- Set Stacks to true — the stack will not be able to grow any larger
- Save
- Start my application
After 2 minutes my program could no longer allocate new memory and I was able to see how everything was handled.
Depending on your applications, it might be easier to limit the memory the language interpreter uses. For example with Java you can set the amount of RAM the JVM will be allocated.
Otherwise it is possible to set it once for each process with the windows API
No way to do this that I know of, although I’m very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.
The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it’s the closest way I know of.
The working set stuff is good (Job Objects also control working sets), but that’s not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn’t limit total allocated memory.