在多线程情况下线程切换会暂用不少的时间,如果指定特定的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();
}
}
}