興之所致,找來一個有趣面試題目來解答:如何能讓CPU 的使用率表現為一條正弦曲線?
這個題目來自《编程之美--微软技术面试心得》,有機會的我會話買下來當作娛樂。
// This program try to burn cpu cycles with a sinusoid function against the time.
#include <MCD/Core/System/TaskPool.h>
#include <MCD/Core/System/Timer.h>
#include <math.h>
class Task : public MCD::TaskPool::Task {
public:
Task(float frequency) : MCD::TaskPool::Task(0), mFrequency(frequency) {}
sal_override void run(MCD::Thread& thread) throw() {
MCD::Timer timer;
while(thread.keepRun()) {
double current = timer.get().asSecond();
double busy = (sin(current * mFrequency) + 1) / 2;
double idle = 1 - busy; // We base on a 1 second interval
while(timer.get().asSecond() < current + busy) {} // Burn CPU cycles
MCD::mSleep(int(idle * 1000)); // Let CPU idle
}
// The Task instance is not needed any more, destroy it.
delete this;
}
float mFrequency;
}; // Task
int main(int, char const*[])
{
const size_t cpuCount = 4; // Set this to match your hardware thread count
const float frequency = 0.1f;
MCD::TaskPool taskPool;
taskPool.setThreadCount(cpuCount);
for(size_t i=0; i<cpuCount; ++i)
taskPool.enqueue(*new Task(frequency));
std::cout << "Press enter to quit...\n";
std::cin.get();
taskPool.stop();
return 0;
}
註:中間的那個高峰因突如其來的 MSN 短訊耗掉了整整一個 CPU Core 而缺了一角。
這題目滿有趣的XD
回覆刪除CPU的使用曲線也能這樣玩。
是哦,久不久找些有趣但又不太花時間的東西玩玩 ^_^
回覆刪除