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

Write code to make CPU usage display a sine wave


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.


Here's a slightly modified @flodin's solution in Python:

#!/usr/bin/env pythonimport itertools, math, time, systime_period = float(sys.argv[1]) if len(sys.argv) > 1 else 30   # secondstime_slice  = float(sys.argv[2]) if len(sys.argv) > 2 else 0.04 # secondsN = int(time_period / time_slice)for i in itertools.cycle(range(N)):    busy_time = time_slice / 2 * (math.sin(2*math.pi*i/N) + 1)    t = time.perf_counter() + busy_time    while t > time.perf_counter():        pass    time.sleep(time_slice - busy_time);    

A CPU-curve can be fine-tuned using time_period and time_slice parameters.


Ok I have a different, probably BETTER solution than my first answer.

Instead of trying to manipulate the CPU, instead hook into the task manager app, force it to draw what you want it to instead of CPU results. Take over the GDI object that plots the graph, etc. Sort of "Cheating" but they didnt say you had to manipulate the CPU

Or even hook the call from task manager that gets the CPU %, returning a sine result instead.