최소 코드 CPU 스트레스 테스터…


28

소개

프로세서를 스트레스 테스트하기 위해 높은 CPU로드를 생성 할 수있는 많은 유틸리티가 있습니다. Microsoft Windows에서는 온보드 calculator.exe를 사용하고와 같은 큰 숫자를 입력 한 999999999후 n!여러 번 눌러 CPU가 초과 작업을 수행 할 수 있습니다.

그러나 직접 만들지 않았다면 어떤 해결책이 있습니까?

미션

당신의 임무는 당신이 그것을 받아들이기로 선택한다면 지구상에서 가장 작은 CPU 스트레스 테스트 툴을 만드는 것입니다.

곰팡내 나게 하다…

  1. 중단 될 때까지 100 % CPU로드를 생성 해야합니다.
  2. 있어야 실행해야합니다 수 초에게 스트레스 테스트를 나타내는 숫자 입력을
  3. 합니다 스트레스 테스트를 중단하기 위해 사용자를 활성화해야합니다 (터미널 창, 또는 그런 일을 닫고, 키를 누를 때) 사용자 상호 작용을 허용 및 / 또는 프로그램을 종료
  4. Microsoft Windows, Mac OSx 및 / 또는 Linux 를 타겟팅 해야합니다 .
    햄스터라도 Comodore64에 스트레스를 줄 수 있으므로 현재 운영 체제를 대상으로 해야합니다 .

하지 말아야 할 것…

  1. 예상되는 기능을 대체하는 타사 프로그램이나 도구를 사용 해서는 안됩니다 .
    (좋아하는 단축키를 제안하면 제안이 system('cpuStressThing.exe')실격됩니다.)

할 수있다…

  1. 수 생산에 어떤 방법 / 알고리즘 / 기능을 사용하여 100 %의 CPU 부하 예상
  2. 수 프로그래밍 또는 스크립트 언어를 사용
    (오래 실행하여 그 기능의 실제적인 검증을 허용하기로)

승리 조건

가능한 가장 작은 소스 코드를 제시하십시오. 우승자는 위의 "필수"및 "필수"조건을 준수하는 가장 작은 (크기) 소스 코드를 제시하는 것입니다. 자, 그 아기를 태워라…


편집하다

질문이 댓글 영역에 나타 났으므로 1 개의 CPU 코어 만 타겟팅하면됩니다. 나는 당신이 멀티 코어 솔루션을 생산할 것으로 기대하지 않습니다. 결국, 이것은 재미 있어야합니다 – 작동하지 않습니다.


5
"한 코어의 100 %"로 충분합니까, 아니면 "멀티 코어 CPU의 100 %"를 의미합니까?
— Tobia

@Tobia Yep, 1 코어면 충분합니다. 해당 정보를 구체적으로 포함하도록 질문을 편집했습니다. 그것이 너무 명확하지 않다는 사실을 알려 주셔서 감사합니다.
— e-sushi

3
cryptocurrency 광부가 계산 /
— TheDoctor

2
@TheDoctor 설명 된 조건에 맞출 수 있다면 ... 내 손님이 되십시오. 파일 크기에서 36 바이트 bash 스크립트 를 이길 수있는 cryptocurrency miner를 보는 것이 확실히 흥미로울 것 입니다.
— e-sushi

문제는 대부분의 광부가 수천 줄의 코드라는 것입니다.
— TheDoctor

답변:


28

배쉬 및 표준 유틸리티, 36 31 22 29 28 26 바이트

yes :|sh&sleep $1;kill $!

2
Bash 코드는 꽤 화려합니다! 정말 좋은 답변입니다!
— Ismael Miguel

당신은 필요가 없습니다 :에를 do :; done. 나는 do;done그 일을한다는 것을 발견 했다-그것은 당신을 2 바이트로 끌어들일 것이다. 또한 내 bash 솔루션 길이의 거의 절반에 대해 +1 (잊어 버린 이유없이 지나치게 복잡하게 만들었습니다 $!).
— Chris J

1
@ChrisJ-그것은 나를 위해 작동하지 않습니다 : bash: syntax error near unexpected token `;'. 나는이 bash는 버전을 시도했다 : 3.00.15(1)-release (x86_64-redhat-linux-gnu), 3.2.48(1)-release (x86_64-apple-darwin12),4.2.25(1)-release (x86_64-pc-linux-gnu)
— 디지털 외상

1
@ChrisJ-나는 당신이 34 바이트 ksh답을 가지고 있다고 생각합니다 ;-)
— Digital Trauma

2
나는 넣어 것 $1대신에 10그냥 "숫자 입력을 받아"라는 스크립트로를 만들기 위해,이.
— Tobia

20

Bash / iputils (Linux), 14 바이트

ping6 -fw$1 ::

-w 최종 기한 타이머가 만료 될 때까지 IPv6 널 주소를 플러딩합니다.

경고-테스트 VM에서 55-60 % CPU 만 소비

편집 :-나는주의를 철회. 프로세스가 CPU를 55-60 % 만 소비한다고 top보고 하지만 ping6총 CPU 유휴 백분율 (2 코어 VM)이 0에 근접한 것으로 보입니다. 이것은 아마도 패킷을 처리 할 때 커널에서 많은 처리가 진행되고 있기 때문일 것입니다.

주 – 루트로 실행해야합니다. @Tobia가 언급했듯이 이것은 CPU를 낭비하는 것에 대한 합리적인 요구 사항처럼 보입니다. 그리고 OP는 의견에서 그것을 승인했습니다.


6
+1. sudo 테스트를 루트로 실행해야한다고 말하고 제거했습니다 . CPU를 낭비하는 것에 대한 합리적인 요구 사항처럼 보입니다.
— Tobia

@Tobia-감사합니다-당신이 무언가에 있다고 생각합니다 ;-)
— Digital Trauma

ping -6 :: -t-> Windows에서 이것이 내 CPU를 열광 시켰을 경우에만 ... 그것은 Windows에서 Linux에 해당하는 것으로 오류가 발생하고 CPU를 1 %로로드하지 않습니다! core2quad 2.63GHz에서 Windows 8 pro x64를 사용하고 있습니다.
— Ismael Miguel

@IsmaelMiguel---이것을 테스트 할 수있는 창이 없습니다. 그렇기 때문에 제목에 "Linux"
— Digital Trauma

나는 내가하고 실패한 것처럼 창문에서 같은 것을 시도하는 것을 생각하는 사람들을 위해이 대답을 작동하지 않는 것으로 단지 "주는"것입니다.
— Ismael Miguel

9

elf32 독립형 바이너리-86 바이트

나는 이것이이 기능을 수행 할 수있는 가장 작고 올바르게 형성된 Elf 형식 바이너리 인 내기 입니다. 이것은 Linux 기반 플랫폼에서 추가 지원 없이 또는 잠재적 으로 운영 체제 없이도 실행됩니다 .

이진 다운로드 : http://ge.tt/3m6h2cK1/v/0?c

육각 덤프 :

0000000: 7f45 4c46 0101 0100 0000 0000 0000 0000  .ELF............
0000010: 0200 0300 0100 0000 5480 0408 3400 0000  ........T...4...
0000020: 0000 0000 0000 0000 3400 2000 0100 0000  ........4. .....
0000030: 0000 0000 0100 0000 0000 0000 0080 0408  ................
0000040: 0080 0408 5600 0000 5600 0000 0500 0000  ....V...V.......
0000050: 0010 0000 75fe                           ....u.

이것은 최소한의 Elf 헤더로 asm 파일을 작성하고 ld완전히 사용하지 않고 수행 됩니다.

어셈블리:

BITS 32

              org     0x08048000

ehdr:                                                 ; Elf32_Ehdr
              db      0x7F, "ELF", 1, 1, 1, 0         ;   e_ident
times 8       db      0
              dw      2                               ;   e_type
              dw      3                               ;   e_machine
              dd      1                               ;   e_version
              dd      _start                          ;   e_entry
              dd      phdr - $$                       ;   e_phoff
              dd      0                               ;   e_shoff
              dd      0                               ;   e_flags
              dw      ehdrsize                        ;   e_ehsize
              dw      phdrsize                        ;   e_phentsize
              dw      1                               ;   e_phnum
              dw      0                               ;   e_shentsize
              dw      0                               ;   e_shnum
              dw      0                               ;   e_shstrndx

ehdrsize      equ     $ - ehdr

phdr:                                                 ; Elf32_Phdr
              dd      1                               ;   p_type
              dd      0                               ;   p_offset
              dd      $$                              ;   p_vaddr
              dd      $$                              ;   p_paddr
              dd      filesize                        ;   p_filesz
              dd      filesize                        ;   p_memsz
              dd      5                               ;   p_flags
              dd      0x1000                          ;   p_align

phdrsize      equ     $ - phdr

section .text
global  _start
_start:       jnz     _start

filesize      equ     $ - $$

내장 nasm -f bin tiny_cpu_stresser_elf32.asm -o tiny_cpu_stresser_elf32


7

bash 내장은 20 바이트 만

ulimit -t $1;exec $0

@ e-sushi는 더 빠른 터미널 (예 : 텍스트 콘솔 또는 xterm 또는 rxvt)을 사용해보십시오
— Geoff Reedy

6

C, 52

t;main(s){for(scanf("%d",&s),t=time();time()-t<s;);}

종료하려면 Ctrl + C를 누르십시오.

enter image description here


PHP에서 그렇게하면 승리 할 것입니다! $i=<>부품을 제거하고 <?시작 부분에 추가 하기 만하면 됩니다.
— Ismael Miguel

5

펄, 32

for($i=<>,$t=time;time-$t<$i;){}

지금 당황 부분 : 나는 어리석게도 넣어 $t=time앞에$i=<> 몇 초 일찍 나가는 이유를 알아 내려고 애 있었다.

다시 Ctrl + C를 눌러 종료하십시오.

enter image description here


5

유닉스 C, 47

main(int a,char**b){alarm(atoi(b[1]));for(;;);}

명령 행에 시간을 전달하십시오. 인터럽트 키 (Ctrl-C)가 중단됩니다.


3
@ace의 scanf트릭 을 사용 하면 39까지 줄일 수 있습니다.main(a){for(scanf("%d",&a),alarm(a);;);}
— Dave

4

스몰 토크 (Smalltalk / X), 34

입력 : n; CTRL-c 또는 CMD-와의 인터럽트

[[]loop]valueWithTimeout:n seconds

일 단위로 측정하면 골프를 더 잘 할 수 있습니다 ;-) (농담) :

[[]loop]valueWithTimeout:n days

enter image description here

또는 명령 행에서 : enter image description here


4

이것은 심각한 시도는 아니지만 ...

배쉬, 12 바이트

:(){ :|:&};:

으로는 발견 위키 백과 .

경고 : 유해한 코드입니다. 컴퓨터에서 실행하지 마십시오!


기술적으로 :
-시스템이 충돌 할 때까지 100 % CPU로드를 생성합니다.
-사용자 상호 작용으로 중지 할 수 있습니다 (모든 포크를 죽이면 실제로 중지 할 수 있습니다 ...);
-실행해야하는 시간 (초)을 나타내는 숫자 입력을 제공 할 수 있지만 사용하지는 않습니다.


4

PHP 43 40 바이트 :

이것이 적절한 답변이기를 바랍니다.

set_time_limit ($ _ REQUEST [ 't']); while (! 0);

<?for(set_time_limit($_REQUEST['t']);;);

나는 이렇게 할 수 <?for(set_time_limit($_POST['t']);;);있지만 유연성과 3 바이트를 잃을 것입니다.


그리고 나는 속일 수 있고 이렇게 할 수 있습니다 : <?for(set_time_limit($_REQUEST[t]);;);. 2 바이트를 줄이지 만 "표준"솔루션은 아닙니다. 게임을 공정하게 유지하십시오.


@fireeyedboy 및 @primo가 제안 했듯이이 솔루션 (34 바이트)을 사용할 수도 있습니다.

<?for(set_time_limit($argv[1]);;);

이를 통해 콘솔에서 다음과 같이 호출 할 수 있습니다.

php <filename> <time in seconds>

내가 말했듯이, 나는 콘솔 솔루션을 목표로하지는 않지만 이것에 대한 크레딧을 얻어야합니다.

또 다른 대답은이 "몬스터"일 수 있으며, 두 답변이 모두 결합 된 것입니다.

<?for(set_time_limit($argv[1]|$_REQUEST['t']);;);

콘솔을 사용하지 않고 PHP로 키를 누르는 것은 불가능합니다.

중지하려면 프로세스를 중단해야합니다 (페이지로드를 중지하면 코드가 중지 될 수 있음).

또한 안드로이드에서도 작동합니다! PHP 서버를 설치 한 경우 (Google Play에서 무료)

작동하려면 간단히 다음과 같이하십시오.

.php 웹 페이지를 작성 ?t=<time in seconds>하고 URL 끝에 추가 하거나 게시물을 제출하십시오 (양식 또는 아약스 사용).


1
@ e-sushi 나는 대답을 수정하고 3 바이트를 줄였습니다. Bash 솔루션만큼 작지는 않지만 가깝습니다. 유연성으로!
— Ismael Miguel

명령 행에서 실행 :로 교체 $_REQUEST['t']한 $argv[1]후로 호출하고로 php -f cpustresstest.php <timelimit>중단하십시오 ^C.
— 알맞은 Dabbler

$_GET대신에 사용 하지 $_REQUEST않겠습니까? 4 바이트를 사용하고 있습니까 GET어쨌든
— 크리스토퍼 Sall이-Storgaard

@KristofferSHansen 내 코드의 유연성이 심각하게 손상되기 때문입니다.
— Ismael Miguel

@fireeyedboy 좋은 생각 인 것 같지만 내가 말했듯이 나는 콘솔을 목표로하지 않습니다.
— Ismael Miguel

3

BrainFuck / Extended BrainFuck : 3

+[]

중단 될 때까지 하나의 코어에서 100 % CPU를 사용합니다. 모든 Brainfuck 프로그램은 유효한 EBF 프로그램입니다.

Zozotez LISP : 7 15 19

작은 드라이버를 사용할 때.

(:'r s) ; redfine read in the read-eval-print-loop

드라이버가없는 독립형 표현으로 : 15

((:'L(\()(L))))     ; setq a loop function and execute it    

용법: echo '((\(L)(L))(\()(L)))' | jitbf zozotez.bf


3

펄-14 바이트

alarm<>;{redo}

a SIGALRM를 input초 단위 로 보내도록 설정 하여 스크립트를 종료합니다. 한편, 그것은 바쁜 대기에서 회전합니다.

샘플 사용법 :

$ echo 4 | perl stress.pl
Terminating on signal SIGALRM(14)

Perl-12 (+1) 바이트

명령 행 옵션이 각각 1 바이트로 계산되면 다음을 사용하여 13 바이트 로 줄일 수 있습니다 -n.

alarm;{redo}

샘플 사용법 :

$ echo 4 | perl -n stress.pl
Terminating on signal SIGALRM(14)

출구 요구 사항을 간결하게 만족시키기 위해 신호를 영리하게 사용하려면 +1
— 기계 달팽이

3

Linux의 x86_64 어셈블리-146 (소스), 42 (어셈블 된 코드)

NASM 축소 소스 (146 바이트) :

xor rdi,rdi
mov rcx,[rsp+16]
mov rcx,[rcx]
l:
sub cl,'0'
jl k
imul rdi,10
movsx rdx,cl
add rdi,rdx
ror rcx,8
jmp l
k:
mov rax,37
syscall
s:
jmp s

명령 줄에서 (0, 9999999] 범위에서 실행할 시간 (초)을 지정하는 매개 변수를 허용하며 일반적인 Ctrl-C로 중단 될 수 있습니다.

당신은 그것을 조립할 수 있습니다

nasm -f elf64 -o stress.o stress.asm && ld -o stress stress.o

이론상 처음 global _start에는 _start:레이블 다음에 레이블 을 추가해야 하지만 ld번거 로움없이 레이블 자체를 고칠 수 있습니다.

해당 기계 코드 (42 바이트) :

00000000  48 31 ff 48 8b 4c 24 10  48 8b 09 80 e9 30 7c 11  |H1.H.L$.H....0|.|
00000010  48 6b ff 0a 48 0f be d1  48 01 d7 48 c1 c9 08 eb  |Hk..H...H..H....|
00000020  ea b8 25 00 00 00 0f 05  eb fe                    |..%.......|
0000002a

( 지시문 을 nasm추가하여 생성 BITS 64)

좀 더 읽기 쉬운 버전 :

global _start

_start:
    xor rdi,rdi
    mov rcx,[rsp+16]
    mov rcx,[rcx]
argparse:
    sub cl,'0'
    jl alarm
    imul rdi,10
    movsx rdx,cl
    add rdi,rdx
    ror rcx,8
    jmp argparse
alarm:
    mov rax,37
    syscall
loop:
    jmp loop

2

파이썬, 58 55 51

Wow... longer than the C one. There's got to be a better way. Still a tad long, but at least it beats the C solution!

import time;t=time.time;u=t()+input()
while t()<u:1

1
Haha, I love your first sentence. Personally I consider a C answer as the par.
— user12205

1
@ace (Barely) Fixed!
— Bob

2
Now the other C solution beats yours!
— user12205

1
@ace Ah, I give up, At least this one is portable! :P (I actually looked at sigalrm earlier, but it's just too expensive to set up and use signals... Python can be rather wordy when its libs are required :[)
— Bob

2

Java - 154 148 186

Weird error ate my Thread.sleep() part

public class Z{public static void main(String[]a) throws Exception{new Thread(){public void run(){for(;;);}.start();Thread.sleep(Byte.valueOf(a[0])*1000);System.exit(0);}}

and a more readable version:

public class Z {
    public static void main(String[] a) throws Exception {
        new Thread() {
            public void run() {
                for (;;)
                    ;
            }
        }.start();
        Thread.sleep(Byte.valueOf(a[0]) * 1000);
        System.exit(0);
    }
}

Spawns a new Thread with a nice endless loop (for(;;);) then on main thread a thread.sleep() and a System.exit(0) after timeout to exit; ctrl-c exits, too on cmdline wasnt able to shorthand that exit(). crashing wont work;


2

Batch, 2 characters

%0

In essence, the program constantly starts itself over and over. Your results may vary, due to processor task allocation priority, but it works for me.


2

Powershell, 18 54 50 bytes

To produce 100% load for all CPU cores.

for($s=date;($s|% AddS* "$args")-ge(date)){sajb{}}
  • The script takes a time in seconds as argument.
  • | AddS* is the shortcut for .AddSeconds() method.
  • sajb is the alias for Start-Job cmdlet.

1
How does this satisfy requirement 2 (must take a numeric input, representing the number seconds the stress-test should run)?
— Οurous

Thanks. Fixed..
— mazzy

1

Linux sh and standard utilities, 14

Recent gnu coreutils includes a timeout utility which is helpful:

 timeout $1 yes

1
Nowhere near 100% CPU for me; it's throttled way too much by having to print I think...is there another command?
— Nick T

timeout $1 yes :|sh - 19 is probably the best you can do and get 100% utilisation. Tempted to steal this for my answer, but I'll be sportsman-like :)
— Digital Trauma

1

Matlab - 19

tic;while toc<5;end

Replace 5 with desired execution time.


1

Go, 215 212 193 bytes (full)

package main
import(."runtime"
f"flag"
."strconv"
."time")
func main(){f.Parse()
c:=NumCPU()*2
t,_:=Atoi(f.Arg(0))
GOMAXPROCS(c)
for;c>0;c--{go(func(){for{Now()}})()}
<-After(Duration(t)*1e9)}

Bonus, stresses all CPU's.

The Now() in the loop is there to kick in the scheduler, Now was the shortest function name I could find in my namespace

If I run go fmt the size increases to 286 277 254 bytes



1

Assembly: 16 bytes

_start:jg _start

Edit: Having not noticed the requirement to take a numeric input, i'm going to claim it does take one on the commandline, but ignores it =)


This takes a numeric input for the number of seconds the test runs? It looks to me like it simply loops infinitely. Whatever it is, remember to add an explanation in your answer.
— Justin

Oh... totally read past that part of the question :/
— Riot

1

DOS Batch - 5 bytes

%0|%0

DOS Batch - 8 bytes

%0|%0&%0

Second is a translation of the infamous sh forkbomb.

Ctrl+C breaks the program (unless you've tweaked the settings a little).


1

C#, 118

using a=System.DateTime;class b{static void Main(string[]c){var d=a.Now.AddSeconds(int.Parse(c[0]));while(d>a.Now){}}}

Uncompressed

using a = System.DateTime;
class b 
{ 
    static void Main(string[] c) 
    {
        var d = a.Now.AddSeconds(int.Parse(c[0]));
        while (d > a.Now) { } 
    } 
}

This requires a number as an argument which is the number of seconds to run. It will use 100% of one core for that much time or until crtl+c. I'm pretty sure this is as small as C# will go with its verbosity.


1

C# - 178 characters

using A=System.DateTime;class P{static void Main(string[]a){var b=A.Now.AddSeconds(int.Parse(a[0]));System.Threading.Tasks.Parallel.For(0,1<<30,(i,l)=>{if(A.Now>b)l.Stop();});}}

And more readable:

using A = System.DateTime;
{ 
    class P 
    {
        static void Main(string[] a)
        { 
            var b = A.Now.AddSeconds(int.Parse(a[0]));
            System.Threading.Tasks.Parallel.For(0, 1 << 30, (i, l) => 
            {
                if (A.Now > b)l.Stop(); 
            });
        }
    }
}

Thats 178 chars in C# and uses all cores.

The only weakness that it is always ending because of the 1<<30 integer limit.


1

Java - 88 characters

class S{public static void main(String[]a){for(long i=0;i<Long.valueOf(a[0]);){i=i+1;}}}

This allows for 2⁶³-1 loops.

More Readable Version

class S {
    public static void main(String[] a) {
      for (long i = 0; i < Long.valueOf(a[0]);) { i = i + 1; }
}

C# - 87 characters

class S{public static void Main(string[]a){for(long i=0;i<long.Parse(a[0]);){i=i+1;}}}

More Readable Version

class S {
public static void Main(string[] a) {
    for(long i = 0;i < long.Parse(a[0]);i++) { i = i + 1; }
}
}

The program pegging the core

(This is on a 4 core system)


OP asked for 100%
— Milo

The OP also specified that you only need to peg one core. It can go to 25% (which is 100% of 1 core).
— Justin Krejcha

2
Not to be picky but your image shows 24.89% not 25%
— Milo

True. It depends on what's happening on that core. If nothing is happening on the core, it will use the full 25%.
— Justin Krejcha

1

EcmaScript 6:

z=z=>{while(1)z()};_=i=>(i+=1,i-=1,i++,i--,--i,++i,i<<=2,i>>=2,i+=0|Math.round(1+Math.random())&1|0,z(x=>setInterval(x=>z(x=>new Worker('data:text/javascript,'+_.toSource()),5))));setInterval(x=>z(x=>_(...Array(i=9e3).map((x,z)=>z*3/2*2/4*4e2>>2<<2))),5)

This will use 100% of the CPU on a single-core machine, and with Firefox, it has the added bonus that Firefox keeps using up more and more memory; the whole interface locks up and the only way to stop it is to kill Firefox in the task manager.


1

perl, 23 bytes

I can't figure out how to paste a literal control-T here, so I've typed $^T instead, but either works (the literal is 1 char shorter at 23 bytes):

$e=$^T+<>;1 until$e<time

$^T is just the time the interpreter started, so you can basically read that as time() since it is the first thing we calculate.


1

Python, 30

I found this old puzzle interesting, I hope it's OK to post an answer to an old question. I just couldn't let the C answers beat Python. ;)

sum(range(int(input())*2**26))

This needs tuned for different CPUs, but I don't think that violates the OP... sum(range(2**27)) pegs one of my 2.8GHz i7 cores for about a second. :)


1
Welcome to PPCG! Posting answers to old questions is perfectly acceptable here, however as far as I see this answer does not full fill the requirement must produce 100% CPU load until aborted.
— Laikoni

Thanks! :) On my machine, this code produces 100% load on a single core, and I can abort it like any other script by pressing Ctrl-C or killing the parent process (e.g., by closing the terminal window) or etc. Note also requirement 2: must take a numeric input, representing the number seconds the stress-test should run. So that the code needs to take user input somehow and self-limit accordingly, as well as just peg a CPU. This is the part I found most interesting about the puzzle...
— James

You're right, thanks for the clarification.
— Laikoni
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.