当前位置:网站首页>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 .
边栏推荐
- 【kotlin 协程】万字协程 一篇完成kotlin 协程进阶
- mysql基础入门 day3 动力节点[老杜]课堂笔记
- Introduction to MySQL foundation power node [Lao Du] class assignment
- 云服务器上部署仿牛客网项目
- 启动jar包报错UnsupportedClassVersionError,如何修复
- Redis设计与实现(六)| 集群(分片)
- Graffiti Wi Fi & ble SoC development slide strip
- 【NVMe2.0b 14-2】Create/Delete Queue
- icon资源
- TiDB v6.0.0 (DMR) :缓存表初试丨TiDB Book Rush
猜你喜欢

电流探头电路分析

Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)

Swagger use

TiDB v6.0.0 (DMR) :缓存表初试丨TiDB Book Rush

A troubleshooting of CPU bottom falling

Gilbert Strang's course notes on linear algebra - Lesson 1

Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"

Pytorch BERT

2021-04-29

【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command
随机推荐
[nvme2.0b 14-7] set features (Part 1)
Sword finger offer II 075 Array relative sort (custom sort, count sort)
Conversion between map, string and JSON
el-input 限制只能输数字
Redis design and Implementation (V) | sentinel sentry
Emoji icons supported by markdown
[untitled]
End-to-end 3D Point Cloud Instance Segmentation without Detection
Summary of common pytoch APIs
Rendering engine development
Gilbert Strang's course notes on linear algebra - Lesson 3
2021-02-22
JVM调优相关命令以及解释
Introduction to MySQL basics day3 power node [Lao Du] class notes
电流探头电路分析
Map,String,Json之間轉換
Flink Exception -- No ExecutorFactory found to execute the application
Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"
Self made GIF dynamic graph -gifcam
Unity简单shader