编程之美学习笔记:Windows下CPU占用率呈正弦曲线实现

// TestCPU.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"
#include "stdlib.h"
#include "math.h"

const double SPLIT = 0.01;
const int COUNT = 200;
const double PI = 3.14159265;
const int INTERVAL = 300;

void SinTest()
{
    DWORD busySpan[COUNT];
    DWORD idleSpan[COUNT];
    int half = INTERVAL/2;
    double radian = 0.0;
    for (int i = 0; i < COUNT; i++)
    {
        busySpan[i] = (DWORD) (half + (sin(PI * radian) * half));
        idleSpan[i] = INTERVAL - busySpan[i];
        radian += SPLIT;
    }

    DWORD startTime = 0;
    int j = 0;
    while (true)
    {
        j = j % COUNT;
        startTime = GetTickCount();
        while ((GetTickCount() - startTime) <= busySpan[j])
        {
            ;
        }
        Sleep(idleSpan[j]);
        j++;
    }
}

const int CPU_PERIOD = 2.8*1000000000; //2.8GHZ

int GetProcessorNum()
{
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);
    return (int)sysInfo.dwNumberOfProcessors;
}

void LineTest()
{
    int cpuNum = GetProcessorNum();
    while (1)
    {
        for (int i = 0; i < (CPU_PERIOD*cpuNum)/5;i++)//for循环转换为汇编需要5个机器命令
        {
            ;
        }
        Sleep(10);//10ms接近window调度时间片
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    //SetThreadAffinityMask(GetCurrentProcess(),0x00000001);
    LineTest();
    //SinTest();
    return 0;
}

待完善。。。

    原文作者:JustSlower
    原文地址: https://blog.csdn.net/cz168love/article/details/44035057
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞