当前位置:网站首页>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 .
边栏推荐
- 【NVMe2.0b 14-2】Create/Delete Queue
- What are the Amazon evaluation terms?
- Redis设计与实现(三)| 服务器与客户端的交互(事件IO模型)
- Redis设计与实现(八)| 事务
- Circuit analysis of current probe
- Sword finger offer II 075 Array relative sort (custom sort, count sort)
- Emoji icons supported by markdown
- Redis设计与实现(二)| 数据库(删除策略&过期淘汰策略)
- Cesium learning notes (I)
- 【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command
猜你喜欢
电流探头电路分析
【NVMe2.0b 14-8】Set Features(下篇)
[kotlin collaboration process] complete the advanced kotlin collaboration process
codeforces每日5题(均1700)-第三天
电流探头的干扰源电流谱测试
【NVMe2.0b 14】NVMe Admin Command Set
Redis design and Implementation (IV) | master-slave replication
Summary of common pytoch APIs
Cesium learning notes (V) custom geometry and appearance
El input limit can only input numbers
随机推荐
Common tools installation, configuration, compilation, link, etc
Tidb 6.0: making Tso more efficient tidb Book rush
[nvme2.0b 14-8] set features (Part 2)
El input limit can only input numbers
Redis设计与实现(三)| 服务器与客户端的交互(事件IO模型)
Does the oscilloscope probe affect the measurement of capacitive load?
Enhance the add / delete operation of for loop & iterator delete collection elements
Is it safe to open an account? How can anyone say that it is not reliable.
Emoji icons supported by markdown
mysql基础入门 动力节点[老杜]课堂作业
[kotlin collaboration process] complete the advanced kotlin collaboration process
Enter the URL in the browser and display it on the page
Redis design and Implementation (I) | data structure & object
Pytorch BERT
MIME类型大全
C#访问SQL Server数据库两种方式的比较(SqlDataReader vs SqlDataAdapter)
Gilbert Strang's course notes on linear algebra - Lesson 1
2021-05-06
维基媒体基金会公布新商业产品“维基媒体企业”首批客户
icon资源