Home > Backend Development > C++ > How to % CPU

How to % CPU

Patricia Arquette
Release: 2025-01-09 06:56:43
Original
408 people have browsed it

How to % CPU

A common question among sysadmins: "How do I quickly generate dummy CPU load on this machine?" If a simple 100% CPU load across one or more cores is sufficient, building a custom solution is surprisingly easy.

The Single-Core Solution (One-Liner)

This single line of C code, compiled and run, will peg one core at 100% utilization:

<code class="language-c">int main() {while (1) {}}</code>
Copy after login

Compile using gcc -o stressme stressme.c (or cl stressme.c on Windows) and run with ./stressme (or stressme.exe). To stress multiple cores, simply run multiple instances of the program.

Multi-Core Solution (Multi-Threaded)

For more controlled multi-core stress testing, consider this multi-threaded version using 4 POSIX threads:

<code class="language-c">#include <pthread.h>
#include <unistd.h>

#define NUM_THREADS 4

void *loop(void *arg) {
    while (1) {}
}

int main() {
    pthread_t threads[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_create(&threads[i], NULL, loop, NULL);
    }
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    return 0;
}</code>
Copy after login

Compile with gcc -o multistress multistress.c -pthread.

How It Works

The core functionality is a simple infinite loop (while (1) {}). At the assembly level, this translates to a continuous jmp instruction, maximizing CPU usage. Modern preemptive multitasking operating systems allow this loop to consume processor time without rendering the system completely unresponsive; the process can still be terminated. In contrast, older cooperative multitasking systems would likely freeze due to such a loop.

<code class="language-assembly">global _start

_start:
    jmp _start</code>
Copy after login

The above is the detailed content of How to % CPU. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template