cpu某一核上正弦曲线c#

从编程之美上抄来的代码效果不是很好,即使前面加上SetProcessAffinityMask(GetCurrentProcess(), 0x00000001);也不行

 

http://www.cnblogs.com/leading/archive/2012/03/21/make_windows_task_manager_show_sine_wave_cpu_usage.html

这篇文章的图很漂亮,但在我的机器上出不来这么好的效果

后来自己用PerformanceCounter做,波峰还不错,波谷不太正常

 private void SetCpuCore()
        {
            
            IntPtr handle = Process.GetProcessesByName("CpuWave.vshost")[0].Handle; //debug

            UIntPtr affinityMask = new UIntPtr(mask);
            ApiHelper.SetProcessAffinityMask(handle, affinityMask);
        }

        public void Start()
        {
            SetCpuCore();

            //避免cpu总是比期望值小而死循环,调整这3个参数可以改变波形美观程度
            float additionalGain = 1.00f;
            double moveAxisUp = 0.4; //理论上应该0.5,但实际发现会死循环
            double amplitudeModifier = 2; 
            int waitForSample = 1;

            PerformanceCounter performanceCounter = new PerformanceCounter("Processor", "% Processor Time", counterInstance, true);
            watch.Start();
            CounterSample s1 = performanceCounter.NextSample();

            while (true)
            {
                long elapsedTime = watch.ElapsedMilliseconds;
                double angelRadian = elapsedTime/1000.0/period*2.0*Math.PI;
                double sineValue = (Math.Sin(angelRadian) / amplitudeModifier + moveAxisUp) * 100.0;

                //Thread.Sleep(1);
                CounterSample s2 = performanceCounter.NextSample();
                float cpu = CounterSampleCalculator.ComputeCounterValue(s1, s2)*additionalGain;
                while (cpu < sineValue)
                {
                    s2 = performanceCounter.NextSample();
                    cpu = CounterSampleCalculator.ComputeCounterValue(s1, s2)*additionalGain;
                }

                s1 = performanceCounter.NextSample();

                Thread.Sleep(waitForSample);
            }
        }

 

 

示例

https://files.cnblogs.com/devourer/CpuWave.7z

posted @ 2013-07-29 14:26  ^^!  阅读(498)  评论(0)    收藏  举报