How to write a program, which uses 30% of CPU? [closed]
This is an interview question: write a program, which uses 30% CPU? How would you write such a program?
maybe this is not what you expected, but try:
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#define IMAX 999999
#define SLEEP 9999
int main( int argc, char *argv[] ) {
long i;
for(;;) {
for(i=0; i<IMAX; i++) {}
usleep(SLEEP);
}
}
experiment with the SLEEP length. This one gave 25% load on my notebook. IMAX 999 gave 76%. without sleep = 100%.
This works on my laptop
Private Sub Form1_Shown(sender As Object, _
e As System.EventArgs) Handles Me.Shown
Dim numProc As Integer = Environment.ProcessorCount
For x As Integer = 1 To numProc
Dim t As New Threading.Thread(AddressOf foo)
t.IsBackground = True
t.Start()
Next
End Sub
Private Sub foo()
Const usage As Double = 0.35 '35%
Dim sleep As Integer = CInt((1 - usage) * 100)
Dim stpw As New Stopwatch
Do
stpw.Reset()
stpw.Start()
Do
Loop While stpw.ElapsedMilliseconds < 100 - sleep
Threading.Thread.Sleep(sleep)
Loop
End Sub
I do wonder, as others have, about the intent of the question.
精彩评论