如何编写一个占用CPU 30%的程序?

发布于 2024-11-05 11:54:09 字数 46 浏览 1 评论 0原文

这是一道面试题:编写一个程序,它使用了30%的CPU?你会如何编写这样的程序?

This is an interview question: write a program, which uses 30% CPU? How would you write such a program?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苦妄 2024-11-12 11:54:09

也许这不是您所期望的,但请尝试:

#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);
    }
}

试验 SLEEP 长度。这给我的笔记本带来了 25% 的负载。 IMAX 999 给了 76%。
不睡觉= 100%。

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%.

永言不败 2024-11-12 11:54:09

这在我的笔记本电脑上有效

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

,我确实像其他人一样想知道这个问题的意图。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文