日期:2014-05-18 浏览次数:21080 次
今天早上看到了编程之美,我很兴奋,大早上看书,有吗? 有木有?
哈哈
?
想想第一节的东西。CPU占用曲线,很经典,导致我很淡定的实现了一个,主要问题
1.我电脑是双核的
2.我CPU周期很不稳定
3.OS内运行了很多东西,比如360等
?
由于以上的原因,我选择了书上给的C#实现,还有就是书上给的多核的建议
?
实现发现,code趋势在49和50左右徘徊
?
CPU50%稳定率为80%左右
?
如果有更好的建议请给我留言
?
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace TestForCPUByCSharp
{
class Program
{
[DllImport("kernel32.dll")]
static extern UIntPtr SetThreadAffinityMask(IntPtr hThread, UIntPtr dwThreadAffinityMask);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
static void Main(string[] args)
{
SetThreadAffinityMask(GetCurrentThread(), new UIntPtr(SetCpuID(1)));
PerformanceCounter p = new PerformanceCounter("Processor", "%Processor Time", "_Total");
while (true)
{
if (p.NextValue() > 0.5)
{
System.Threading.Thread.Sleep(10);
}
}
}
static ulong SetCpuID(int id)
{
ulong cpuid = 0;
if (id < 0 || id >= System.Environment.ProcessorCount)
{
id = 0;
}
cpuid |= 1UL << id;
return cpuid;
}
}
}
?
?