Allocate CPU to run your process on 1 core using C ++

I am working on a project that measures the impact of some code on a CPU. To do this, I need to start my process on the CPU and stop all other processes on the CPU in order to see the real effect of my process.

I also need to run my process on 1 processor core. Can anyone help how to do this in C ++?

+6
source share
4 answers

You can adjust the proximity of the processor to the process. When you do this, your process will only work on this CPU. This way you can measure the performance of your process. So I did for the service in VC ++. Hope this will be helpful.

SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); HANDLE hProcess = GetCurrentProcess(); if(SystemInfo.dwNumberOfProcessors >1) { //DWORD dwProcessAffinityMask, dwSystemAffinityMask; //GetProcessAffinityMask( hProcess, &dwProcessAffinityMask, &dwSystemAffinityMask ); //SetProcessAffinityMask( hProcess, 1L );// use CPU 0 only //SetProcessAffinityMask( hProcess, 2L );// use CPU 1 only //SetProcessAffinityMask( hProcess, 3L );// allow running on both CPUs SetProcessAffinityMask( hProcess, 2L );// use CPU 1 only } 
+1
source

The C ++ standard does not allow the establishment of thread affinity. To do this, you will need to use boost or your system API.

NOTE. Although explicit affinity management can lead to large rewards, it is also risky. This can lead to disabling some optimizations implemented by the system's own scheduler, which is especially bad when the processes that you control using this method are not the most difficult on your system. In addition, affinity management can quickly go wrong: imagine that you accidentally load 90% of your load onto one or two cores on your (todayโ€™s usual) octo-cardiac system. Ultimately, Affinity management will need AI to work well in the increasingly complex systems that we encounter, but a simple rule-based management can work well if you can accurately predict the process load.

EDIT: so that your OS does not plan anything else in this kernel, you will need another OS function. As mentioned in the comments, isolcpus allows this to be achieved on Linux.

+1
source

ckv responds with a winapi example. Here is a linux example:

 #include <sched.h> cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(0, &mask); CPU_SET(2, &mask); result = sched_setaffinity(0, sizeof(mask), &mask); 
+1
source

To really stop all other code running on the CPU, you probably have to write your code as an operating system driver or even work without an OS. If a random minor interruption is in order, you can set the priority of a process with a very high priority. This will minimize the time that other processes will โ€œstealโ€ from your code.

What operating system are you using?

0
source

Source: https://habr.com/ru/post/959055/