把上一節的通過C++ 控制CPU的占用率顯示正弦曲線的代碼用C# 重寫了一次,效果要好一點。
上一節的連接: http://www.BkJia.com/kf/201110/107759.html
C#代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace cpu_4_2_csharp
{
class Program
{
static void Main(string[] args)
{
const int SAMPLING_COUNT = 200;
const double PI = 3.14159;
const int TOTAL_AMPLITUDE = 250; // the length of each time piece
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)
{
startTick = Environment.TickCount;
while ((Environment.TickCount - startTick) < busySpan[j])
{
//
}
System.Threading.Thread.Sleep(TOTAL_AMPLITUDE-(int)busySpan[j]);
}
}
}
}
效果圖:
1. 時間片為300
2. 時間片為250
3. 時間片為200
摘自:Watkins.Song