- Analyze CPU usage without debugging in the Performance Profiler
- Collect CPU usage data
- Analyze the CPU Usage report
- CPU Usage data columns
- The CPU Usage call tree
- Call tree structure
- External code
- Asynchronous functions in the CPU usage call tree
- 990x.top
- Простой компьютерный блог для души)
- CPU Usage что это такое?
- Как успокоить процесс, который грузит нереально проц?
- Prometheus: разбираемся с CPU Usage
- Mar 3, 2016 21:43 · 363 words · 2 minute read prometheus monitoring
Analyze CPU usage without debugging in the Performance Profiler
A good way to start investigating performance issues in your app is to understand its CPU usage. The CPU Usage performance tool shows the CPU time and percentage spent executing code in C++, C#/Visual Basic, and JavaScript apps.
The CPU Usage tool can run on an open Visual Studio project, on an installed Microsoft Store app, or attached to a running app or process. You can run the CPU Usage tool with or without debugging. For more information, see Run profiling tools with or without the debugger.
The following instructions show how to use the CPU Usage tool without the debugger, using the Visual Studio Performance Profiler. The examples use a Release build on a local machine. Release builds provide the best view of actual app performance. To analyze CPU usage with Debug builds (debugger attached), see Beginner’s guide to performance profiling.
Usually, the local machine best replicates installed app execution. To collect data from a remote device, run the app directly on the device, not over a Remote Desktop Connection.
Windows 7 or later is required to use the Performance Profiler.
Collect CPU usage data
In the Visual Studio project, set the solution configuration to Release and select Local Windows Debugger (or Local Machine) as the deployment target.
Select Debug > Performance Profiler.
Under Available tools, select CPU Usage, and then select Start.
After the app starts, the diagnostic session begins and displays CPU usage data. When you’re finished collecting data, select Stop Collection.
The CPU Usage tool analyzes the data and displays the report.
Analyze the CPU Usage report
The diagnostic report is sorted by Total CPU, from highest to lowest. Change the sort order or sort column by selecting the column headers. Use the Filter dropdown to select or deselect threads to display, and use the Search box to search for a specific thread or node.
Starting in Visual Studio 2019, you can click the Expand Hot Path and Show Hot Path buttons to see the function calls that use the highest percentage of the CPU in the call tree view.
CPU Usage data columns
Name | Description |
---|---|
Total CPU [unit, %] |
The milliseconds and CPU percentage used by calls to the function, and functions called by the function, in the selected time range. This is different from the CPU Utilization timeline graph, which compares the total CPU activity in a time range to the total available CPU.
The milliseconds and CPU percentage used by calls to the function in the selected time range, excluding functions called by the function.
The CPU Usage call tree
To view the call tree, select the parent node in the report. The CPU Usage page opens to the Caller/Callee view. In the Current View dropdown, select Call Tree.
Call tree structure
Image | Description |
---|---|
The top-level node in CPU Usage call trees is a pseudo-node. | |
In most apps, when the Show External Code option is disabled, the second-level node is an [External Code] node. The node contains the system and framework code that starts and stops the app, draws the UI, controls thread scheduling, and provides other low-level services to the app. | |
The children of the second-level node are the user-code methods and asynchronous routines that are called or created by the second-level system and framework code. | |
Child nodes of a method have data only for the calls of the parent method. When Show External Code is disabled, app methods can also contain an [External Code] node. |
External code
System and framework functions that are executed by your code are called external code. External code functions start and stop the app, draw the UI, control threading, and provide other low-level services to the app. In most cases, you aren’t interested in external code, so the CPU Usage call tree gathers the external functions of a user method into one [External Code] node.
To view the call paths of external code, on the main diagnostic report page (right pane), select Show External Code from the Filter dropdown, and then select Apply. The Call Tree view of the CPU Usage page then expands the external code calls. (The Filter dropdown is available on the main diagnostic page, not the detailed views.)
Many external code call chains are deeply nested, so the width of the chain can exceed the display width of the Function Name column. The function names then appear as . .
To find a function name you’re looking for, use the search box. Hover over the selected line or use the horizontal scroll bar to view the data.
Asynchronous functions in the CPU usage call tree
When the compiler encounters an asynchronous method, it creates a hidden class to control the method’s execution. Conceptually, the class is a state machine. The class has compiler-generated functions that asynchronously call the original methods, and the callbacks, scheduler, and iterators needed to run them. When a parent method calls the original method, the compiler removes the method from the execution context of the parent, and runs the hidden class methods in the context of the system and framework code that controls app execution. The asynchronous methods are often, but not always, executed on one or more different threads. This code appears in the CPU Usage call tree as children of the [External Code] node immediately below the top node of the tree.
In the following example, the first two nodes under [External Code] are the compiler-generated methods of the state machine class. The third node is the call to the original method.
Expand the generated methods to show what’s going on:
MainPage::GetMaxNumberAsyncButton_Click just manages a list of the task values, computes the maximum of the results, and displays the output.
MainPage+ d__3::MoveNext shows you the activity required to schedule and launch the 48 tasks that wrap the call to GetNumberAsync .
MainPage:: b__b shows the activity of the tasks that call GetNumber .
990x.top
Простой компьютерный блог для души)
CPU Usage что это такое?
Приветствую друзья. Тема сегодня о процессорах, а вернее о том что означает словосочетание CPU Usage. Значит смотрите, CPU это процессор, эта аббревиатура расшифровывается как central processing unit, ну типа центральный процессор юнит, последнее слово не знаю что значит. Слово Usage означает использовать. То есть можно сделать вывод, что CPU Usage означает использование процессора.
Словосочетание CPU Usage вы можете встретить где угодно, начиная от самой винды и заканчивая всякими программами. И почти всегда это словосочетание необходимо чтобы проинформировать пользователя об уровне загрузки процессора
Часто пользователей интересует почему CPU Usage 100, что это имеется ввиду? Нагрузка процессора равна 100%. То есть какая-то программа грузит адски процессор. Я дам несколько советов что можно в таком случае предпринять. Узнавать какая именно программа, а вернее какой процесс грузит проц, нужно в диспетчере задач. Для примера я создам искусственную нагрузку при помощи архиватора WinRAR, я просто в нем запущу тест производительности. Первое что нужно сделать, узнать точно процесс, который грузит, для этого жмем на ЦП в диспетчере (вкладка процессы):
После этого нам сразу станет ясно, какой засранец грузит ПК. По крайней мере увидим имя процесса. Если это имя нам ни о чем не говорит, тогда смотрим в колонку описание. В моем случае сразу понятно кто этот засранец:
Это WinRAR archiver. Если нажать правой кнопкой по процессу и выбрать пункт Открыть место хранения файла:
То будет открыта папка, откуда запускается процесс, обычно это и есть папка программы.
Как успокоить процесс, который грузит нереально проц?
Вы можете возразить, мол зачем успокаивать, если можно просто нажать правой кнопкой по процессу и выбрать пункт Завершить. Логично, но не всегда корректно. Если принудительно завершить процесс, то это может повлечь за собой ошибку или прерывание важной задачи. Например процесс TrustedInstaller.exe у многих вызывает большую нагрузку, но не все знают, за что отвечает процесс. TrustedInstaller.exe выполняет установку модулей Windows, на деле это имеется ввиду установка обновлений. Разумеется что при завершение данного процесса прерывается установка обновлений. Как следствие будут ошибки в журнале, которые не факт что будут исправлены центром обновления. Я отвлекся, прошу прощения.
Итак, всего есть два варианта, при которых вы не завершаете грузящий процесс, но снижаете его нагрузку на проц. Первый, это приоритет. Вы можете задать низкий приоритет грузящему процессу, чтобы все остальные процессы получили на фоне его приоритет выше. Для этого нажмите правой кнопкой по процессу и выберите в меню Приоритет > Низкий:
Данная процедура эффективная и в большинстве случаев приносит желаемый эффект.
Второй вариант более агрессивный, поэтому его стоит использовать в крайних случаях. И еще данный вариант не подходит, если у вас одноядерный процессор, однако это редкость. Способ заключается в том, что процесс будет использовать не два ядра процессора, ну или больше, а одно. Если у вас 4 ядра, то можете отдать процессу 2 ядра, или 1, тут уже сами смотрите по ситуации. Чтобы это дело провернуть, нажимаете правой кнопкой по процессу и выбираете пункт Задать соответствие:
У меня в процессоре 2 ядра, поэтому я оставляю процессу 1 ядро:
Если галочка стоит, то ядро будет использоваться. Я поставил галочку на ЦП 0, но можно было и на ЦП 1, разницы нет. Если при этом еще и выставить низкий приоритет, то процесс точно перестанет грузить комп. Однако стоит учесть, что данная процедура увеличит время выполнения задачи процессом. То есть выполнять будет дольше, но зато нагрузка на проц будет максимально снижена
Надеюсь предоставленная информация была полезной. Удачи и до новых встреч ребята!
Prometheus: разбираемся с CPU Usage
Mar 3, 2016 21:43 · 363 words · 2 minute read prometheus monitoring
Высокая нагрузка на процессор часто является причиной проблем в работе сервера и, как следствие, всей системы в целом.
Давайте разберемся с CPU usage с помощью системы мониторинга Prometheus и ее компонента node_exporter !
Считаем, что необходимые компоненты у нас уже установлены и настроены.
В таком случае, на странице метрик, которые собирает компонент node_exporter (например, http://[IP-адрес сервера]:9100/metrics), можем найти примерно следующее:
Данные для этих метрик берутся из файла /proc/stat и отображают время (в USER_HZ — сотых долях секунды), которое CPU расходует на выполнение задач. Эти задачи бывают нескольких типов:
- user — время выполнения обычных процессов, которые выполняются в режиме пользователя (в user mode, userland);
- nice — время выполнения процессов с приоритетом nice, которые выполняются в режиме пользователя;
- system — время выполнения процессов, которые выполняются в режиме ядра (kernel mode);
- idle — время простоя, CPU ничем не занят;
- iowait — время ожидания I/O операций;
- irq и softirq — время обработки аппаратных и программных прерываний;
- steal — время, которое используют другие операционные системы (при виртуализации);
- guest — время выполнения «гостевых» процессов (при виртуализации).
Общее время выполнения этих задач и есть CPU usage (вместе с временем бездействия). Высокое значения времени iowait может означать, что в вашей системе узким местом является дисковая подсистема или сеть.
Чтобы оценить, чем занимается процессор, открываем в браузере веб-интерфейс Prometheus (http://[IP-адрес сервера]:9090) и в поле Expression вводим например такую метрику: irate(node_cpu
Чтобы получить общее значение CPU usage (сумма времен выполнения задач по всем процессорам/ядрам) для отдельного хоста можно использовать следующую метрику: sum by (mode, instance) (irate(node_cpu
Для отображения общего времени работы процессора (сумма времен выполнения задач по всем процессорам/ядрам без учета типа idle ) в процентах можно использовать следующую метрику: 100 — (avg by (instance) (irate(node_cpu