Write a program to keep CPU usage as sin funcion

Imported from: renren.

It is said that this is a problem from interview of Microsoft. Write a program, which makes the CPU usage curve in Windows Task Manager shows a Sin function.

Sine function 1 Sine function 2

The program below is written in java:

public class sincpu {
    private static final int cycle=1024,tick = 256;
    public static void main (String[] args) throws InterruptedException {
        for(int i = 0;;i++){
            work(calcNextSleep(i % cycle));
            sleep(tick - calcNextSleep(i % cycle));

    private static long calcNextSleep(long i){
        return (int)(Math.sin((double)i * 2 * Math.PI / cycle) * tick + tick) / 2;

    private static void sleep (long sleepTime) throws InterruptedException
        if(sleepTime < 2)

    private static void work (long period) {
        long start = System.currentTimeMillis();
            if(System.currentTimeMillis() - start >= period)

Be careful you need to turn off other cores if you have multi-core CPU.

multi-core CPU
Leave a comment from this post's issue page using your Github account.
comments powered by Disqus