http://blog.csdn.net/weixingstudio/article/details/6871235 中指出可以指定线程的运行时指定的CPU,这样,在一个CPU空闲的时候,可以让另外一个CPU进行运算, 同时在任务管理器中显示两个曲线,一个正弦曲线,一个余弦曲线。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace cpu_4_3
{
class Program
{
static void Main(string[] args)
{
const int SAMPLING_COUNT = 200;
const double PI = 3.14159;
const int TOTAL_AMPLITUDE = 100; // the length of each time piece
const float CPU2_BUSY_TIME_LOW = 0.3F;
const float CPU2_BUSY_TIME_HIGH = 0.7F;
//const int system_busy = 10; // take the system cpu consume into consideration
Process p = Process.GetCurrentProcess();
p.ProcessorAffinity = (IntPtr)0x0001;
double[] busySpan = new double[SAMPLING_COUNT];
int amplitude = (TOTAL_AMPLITUDE) / 2;
double radian = 0.0;
double radianIncreament = 2.0 / (double)SAMPLING_COUNT;
for (int i = 0; i < SAMPLING_COUNT; i++)
{
busySpan[i] = ((double)(amplitude + Math.Sin(PI * radian) * amplitude));
radian += radianIncreament;
}
int startTick = Environment.TickCount;
for (int j = 0; ; j = (j + 1) % SAMPLING_COUNT)
{
p.ProcessorAffinity = (IntPtr)0x0001;
startTick = Environment.TickCount;
while ((Environment.TickCount - startTick) < busySpan[j])
{
//
}
p.ProcessorAffinity=(IntPtr)0x0002; // during the process 1 idle time, change to processor 2.
startTick = Environment.TickCount;
// cycle in the processor 2 time.
while ((Environment.TickCount - startTick) < ((TOTAL_AMPLITUDE-(int)busySpan[j])))
{
//int cpu2_sleep_time;
judge from j, verify the period of the process 2.
//if (j <= 125)
//{
// // in this part, the cpu rate is controlled to 30%
// int cpu2_time = 250 - (int)busySpan[j];
// int cpu2_time_busy_low = (int)(cpu2_time * CPU2_BUSY_TIME_LOW);
// cpu2_sleep_time = cpu2_time - cpu2_time_busy_low;
// while ((Environment.TickCount - startTick) < cpu2_time_busy_low)
// { }
//}
//else
//{
// // in this part, the cpu rate is controlled to 70%
// int cpu2_time = 250 - (int)busySpan[j];
// int cpu2_time_busy_high = (int)(cpu2_time * CPU2_BUSY_TIME_HIGH);
// cpu2_sleep_time = cpu2_time - cpu2_time_busy_high;
// while ((Environment.TickCount - startTick) < cpu2_time_busy_high)
// { }
//}
//System.Threading.Thread.Sleep(cpu2_sleep_time);
}
}
}
}
}
注释掉的部门不用管,我用来测试其他的部分的。在CPU1空闲的时候,不让线程sleep,而是将当前进程转移到CPU2上,控制CPU2的繁忙和空闲的时间比例,同时也在CPU2上显示余弦曲线。
这次因为是同时使用两个CPU,可能操作系统自带的很多服务和其他软件会对效果产生影响,所以要调整时间片,我调到100。
效果如图: