Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

windows - Write code to make CPU usage display a sine wave

Write code in your favorite language and let Windows Task Manager represent a sine wave in CPU Usage History.

This is a technical interview quiz from Microsoft China. I think it's a good question. Especially it's worth knowing how candidate understand and figure out the solution.

Edit: It's a good point if may involve multi-core(cpu) cases.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A thread time slice in Windows is 40ms, iirc, so that might be a good number to use as the 100% mark.

unsigned const TIME_SLICE = 40;
float const PI = 3.14159265358979323846f;
while(true)
{
    for(unsigned x=0; x!=360; ++x)
    {
        float t = sin(static_cast<float>(x)/180*PI)*0.5f + 0.5f;
        DWORD busy_time = static_cast<DWORD>(t*TIME_SLICE);
        DWORD wait_start = GetTickCount();
        while(GetTickCount() - wait_start < busy_time)
        {
        }
        Sleep(TIME_SLICE - busy_time);    
    }
}

This would give a period of about 14 seconds. Obviously this assumes there is no other significant cpu usage in the system, and that you are only running it on a single CPU. Neither of these is really that common in reality.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...