《编程之美》读书笔记--让cpu占用率曲线听你的指挥

《编程之美》读书笔记

1.1让cpu占用率曲线听你的指挥

涉及的api函数:

GetTickCount

Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.

Sleep

VOID WINAPI Sleep(

__in DWORD dwMilliseconds

);

Suspends the execution of the current thread for at least the specified interval.

GetCurrentProcess

Retrieves a pseudo handle for the current process

HANDLE WINAPI GetCurrentProcess(void);

SetProcessAffinityMask

Sets a processor affinity mask for the threads of the specified process.

BOOL WINAPI SetProcessAffinityMask(

__in HANDLE hProcess,

__in DWORD_PTR dwProcessAffinityMask

);

 

cpu占用率定义:

在任务管理器的一个刷新周期内,cpu执行应用程序的时间和刷新周期总时间的比率就是cpu占用率。

所以通过在一个刷新时期内调节忙和闲的比例就可以控制占用率。

怎么实现忙:空循环

怎么实现闲:挂起当前运行的线程

 

1.控制cpu占用率为50%

#include<iostream>

#include<windows.h>

using namespace std;

int main(void)

{

    int busytime = 1;

    int idletime = busytime;

    while(1)

    {

        DWORD starttime = ::GetTickCount();

        while((GetTickCount() - starttime) <= busytime)

            ;

        ::Sleep(idletime);

    }

    return 0;

}

2.控制cpu占用率为正弦曲线

 

多核cpu下的曲线:

由书上的提示及在网上搜一下在多核cpu下这个问题的解决方法:

改进后

#include<iostream>

#include<windows.h>

#include<stdlib.h>

#include<math.h>

using namespace std;

 

const double SPLIT = 0.01;

const int COUNT = 200;

const double PI = 3.14159265;

const int INTERVAL = 300;

int main(void)

{

    ::SetProcessAffinityMask(GetCurrentProcess(),0x00000001);

    DWORD busySpanArray[COUNT];

    DWORD idleSpanArray[COUNT];

    double radian = 0.0;

    int half = INTERVAL / 2;

    for(int i = 0; i < COUNT; i++)

    {

        busySpanArray[i] = (DWORD)(half + (sin(PI * radian) * half));

        idleSpanArray[i] = INTERVAL - busySpanArray[i];

        radian += SPLIT;

    }

    DWORD startTime = 0;

    int j = 0;

    while(true)

    {

        j = j % COUNT;

        startTime = ::GetTickCount();

        while((::GetTickCount() - startTime) <= busySpanArray[j])

            ;

        Sleep(idleSpanArray[j]);

        j++;

    }

    return 0;

}

很明显平滑了很多:

因为指定了某个核运行。

posted @ 2011-01-25 21:25  xfate  阅读(438)  评论(0编辑  收藏  举报