当前位置:网站首页>Bind threads to run on a specific CPU logical kernel
Bind threads to run on a specific CPU logical kernel
2022-06-30 08:37:00 【The bright moon is like me】
It is said that in the process of calculation , Switching the logical kernel will cause additional overhead , Affect the efficiency of program operation . Recently started to try simulation optimization (Sim-Opt) Research in , It happens that this content is involved in the requirements . So I made some attempts .
On the first code :
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Management;
namespace BandThreadToCPU
{
class Program
{
//SetThreadAffinityMask: Set hThread run on logical processer(LP:) dwThreadAffinityMask
[DllImport("kernel32.dll")]
static extern UIntPtr SetThreadAffinityMask(IntPtr hThread, UIntPtr dwThreadAffinityMask);
//Get the handler of current thread
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
//The real function
public static void ChangeValue(object lpIdx)
{
//Bind current thread to a specific logical processer
ulong LpId = SetCpuID((int)lpIdx);
SetThreadAffinityMask(GetCurrentThread(), new UIntPtr(LpId));
// Let program run for a while
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
{
for (int j = 0; j < 1000000; j++)
{
int _data = j;
}
}
stopwatch.Stop();
Console.WriteLine("Running Time: " + stopwatch.ElapsedMilliseconds.ToString());
}
//Get CPU id. index:0 -> id:1, 1->2, 2->4, 3->8, 4->16, ...
static ulong SetCpuID(int lpIdx)
{
ulong cpuLogicalProcessorId = 0;
if (lpIdx < 0 || lpIdx >= System.Environment.ProcessorCount)
{
lpIdx = 0;
}
cpuLogicalProcessorId |= 1UL << lpIdx;
return cpuLogicalProcessorId;
}
static void Main(string[] args)
{
// Specify the cpu logical processor index you want. CPU lp index start from 0
int LOGICAL_PROCESSOR_IDX = 4;
// Get the ManagementClass object
ManagementClass mc = new ManagementClass(new ManagementPath("Win32_Processor"));
// Get the properties in the class
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
PropertyDataCollection properties = mo.Properties;
// Print CPU properties
foreach (PropertyData property in properties)
{
Console.WriteLine( property.Name + ": " + property.Value);
}
}
Stopwatch stopwatch = new Stopwatch();
Thread thread = new Thread(new ParameterizedThreadStart(ChangeValue));
stopwatch.Start();
thread.Start(LOGICAL_PROCESSOR_IDX);
thread.Join();
stopwatch.Stop();
Console.WriteLine("Total running time: " + stopwatch.ElapsedMilliseconds.ToString());
Console.ReadKey();
}
}
}
among :
SetThreadAffinityMask Will thread and core Binding .
GetCurrentThread Get the handle of the current thread .
ChangeValue The real business operation logic is here , Here is Demo, So there is only a time-consuming loop written in it .
SetCpuID Here is the more interesting ,CPU Logical processor index (index) It's from 0 At the beginning , however SetThreadAffinityMask When binding, you need to use the logical processor ID,index and id a 2 Exponential power relation of . namely :idx=0 Corresponding id=1(2 Of 0 Power );idx=3 Corresponding id=8(2 Of 3 Power ).
The operation effect is as follows , You can see ,04 Number CPU core It's full , But other core Did not come to help .
This article mainly refers to jimmy-yang The article :《C# The thread is bound to the specified cpu》 The main part of the code also comes from this . The main focus is on code simplification , Deleted parts irrelevant to the main purpose , And changed the names of some variables or functions , Modified comments . Make the key content more prominent , Easy to understand .
边栏推荐
- Flink 数据偶尔数据积压导致checkpoint失败
- Swagger use
- Unity basic lighting model
- End-to-end 3D Point Cloud Instance Segmentation without Detection
- Cesium learning notes (IV) visual image & Terrain
- Source code interpretation of detectron2 1--engine
- 2021-02-22
- Build a docker image of Henkel database from 0
- 【NVMe2.0b 14-3】Doorbell Buffer Config command、Device Self-test command
- Redis design and Implementation (III) | interaction between server and client (event IO model)
猜你喜欢

【NVMe2.0b 14-3】Doorbell Buffer Config command、Device Self-test command

swagger使用

【NVMe2.0b 14-3】Doorbell Buffer Config command、Device Self-test command

【NVMe2.0b 14】NVMe Admin Command Set

电流探头电路分析

【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command

Interference source current spectrum test of current probe

Deploy the cow like customer network project on the ECS

Redis design and Implementation (I) | data structure & object

【NVMe2.0b 14-2】Create/Delete Queue
随机推荐
JVM调优相关命令以及解释
【NVMe2.0b 14】NVMe Admin Command Set
基于Svelte3.x桌面端UI组件库Svelte UI
php api获取二维码、组合生成图片
小心transmittable-thread-local的这个坑
Axure制作菜单栏效果
A troubleshooting of CPU bottom falling
El input limit can only input numbers
Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)
Sword finger offer II 075 Array relative sort (custom sort, count sort)
2021-05-17
Flink sql -- No factory implements ‘org.apache.flink.table.delegation.ExecutorFactory‘.
将线程绑定在某个具体的CPU逻辑内核上运行
【NVMe2.0b 14-4】Directive Send/Receive command
【NVMe2.0b 14-6】Format NVM、Keep Alive、Lockdown command
Flink SQL 自定义 Connector
[untitled]
Axure make menu bar effect
Cesium learning notes (V) custom geometry and appearance
Unity basic lighting model