Write code to make CPU usage display a given graph


  • 6
    G

    Question description:

    Write code to make CPU usage (e.g. in Task Manager on Windows) display the following graphs.

    1. CPU usage is fixed at 50%, making the graph a horizontal line.
    2. CPU usage is fixed at a user given percentage (passed from command line arguments), making the graph a horizontal line.
    3. CPU usage is ups and downs, making the graph a Sine wave.

    Where have you first heard of this question:

    I first heard of this question from a Chinese book written in 2008 whose title is "编程之美" (means The beauty of programming) which includes many interview problems at Microsoft. (Book URL: https://www.amazon.cn/dp/B0016K8XGQ)

    I think it's more appropriate to classify this problem to the System Design category, since it involves some specific Operating System details which differs from different ones.


  • 6
    G

    A brief explanation of your solution:

    In the Chinese book written in 2008 whose title is "编程之美" (means The beauty of programming) which includes many interview problems at Microsoft. (Book URL: https://www.amazon.cn/dp/B0016K8XGQ), there is a detailed discussion about several solutions. And it's mainly about write a program with a infinite loop in which there is a "busy" step and a "idle" step. The "busy" step can be implemented by a empty loop, and the "idle" step is usually implemented by the thread's Sleep operation. By controlling the ratio of "busy" to "idle", it will get the desired CPU usage points in the graph over time.

    Besides, I find some other articles as reference:


  • 3
    I

    This is OS section, we should really be taking advantage of shell scripting:

    #!/bin/bash
    # 
    # Let us take advantage of multi-core hardware
    # This will only work for even number of cores
    #
    number_of_cpus=`getconf _NPROCESSORS_ONLN`
    half_cpus=$((number_of_cpus/2))
    
    if [ $half_cpus -lt 1 ];
    then
    	echo "Too few cores, sorry"
            exit
    fi
    
    for i in `seq 1 ${half_cpus}`;
    do
    	echo $i
    	dd if=/dev/zero of=/dev/null & # each process takes 100% of one core
    done
    

    Works like a charm on my 4-core macbook air

    Well, technically it is at 55%, but that extra 5% is me taking a screenshot.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.