C#线程绑定到指定cpu

在多线程情况下线程切换会暂用不少的时间,如果指定特定的cpu能明显提高程序的执行效率,随着线程数目的增加效果越明显。

这里电脑配置为i3双核4线程 创建8个线程每两个线程绑定到一个虚拟内核。核心号分别为0 1 4 8

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using System.Management;

namespace noBand
{
    class Program
    {
        //获取系统运行时间毫秒级别
         [DllImport("kernel32.dll")]
         static extern uint GetTickCount();


         //SetThreadAffinityMask 指定hThread 运行在 核心 dwThreadAffinityMask
         [DllImport("kernel32.dll")]
         static extern UIntPtr SetThreadAffinityMask(IntPtr hThread,
         UIntPtr dwThreadAffinityMask);

         //得到当前线程的handler
         [DllImport("kernel32.dll")]
         static extern IntPtr GetCurrentThread();

         static int busyTime = 10;
         static int idleTime = busyTime;
        //设置线程数目
        static int threads =8;
    
        public static void changeValue(object pid)
        {
            int core = (int)pid;
            int len=10000000;
            uint[] data=new  uint[len];
          
            //将当前线程绑定到指定的cpu核心上
         SetThreadAffinityMask(GetCurrentThread(), new UIntPtr(SetCpuID(core)));
          
                uint startTime = GetTickCount();
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                
                for (int i = 0; i < len; ++i)
                    data[i] = GetTickCount();

                

                stopwatch.Stop();
                Console.WriteLine("运行时间" + stopwatch.ElapsedMilliseconds.ToString());

        }
        //获取cpu的id号
        static ulong SetCpuID(int id)
        {
            ulong cpuid = 0;
            if (id < 0 || id >= System.Environment.ProcessorCount)
            {
                id = 0;
            }
            cpuid |= 1UL << id;
         
            return cpuid;
        }
        static void Main(string[] args)
        {
<span style="white-space:pre">	</span><span style="color:#ff0000;">//这里需要将Management引用</span>
            // Get the WMI class
            ManagementClass c = new ManagementClass(
            new ManagementPath("Win32_Processor"));
            // Get the properties in the class
            ManagementObjectCollection moc = c.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                PropertyDataCollection properties = mo.Properties;
                //获取内核数代码
                string cpu= "物理内核数:" + properties["NumberOfCores"].Value + "\r";
                string total = "逻辑内核数:" + properties["NumberOfLogicalProcessors"].Value + "\r";
                Console.WriteLine(cpu);
                //其他属性获取代码
                //foreach (PropertyData property in properties)
                //{
                //    Console.WriteLine( property.Name + ":" + property.Value + "\r");
                //}
            }
            //线程数目
            int num = threads;
            Console.WriteLine("线程数目" + num);
            Thread[] t = new Thread[num];
            Stopwatch stopwatch= new Stopwatch();
            
            for (int i = 0; i < num; ++i)
                t[i] = new Thread(new ParameterizedThreadStart(changeValue)); ;
            stopwatch.Start();
            

            for (int i = 0; i < num; ++i)
            {
                t[i].Start(i/2);
            }


                for (int i = 0; i < num; ++i)
                    t[i].Join();
            stopwatch.Stop();
            Console.WriteLine("总运行时间" + stopwatch.ElapsedMilliseconds.ToString());
            Console.ReadKey();
        }
    }
}


  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值