开发者

Need Program that will make the CPU run at 100%

I need a program, that will make my CPU run at 100%.

Preferably in C, a tiny program, that will make the C开发者_Python百科PU run at 100%, and one, that is not "optimized" by the compiler, so it does nothing.

Suggestions?


int main(void) {
  volatile unsigned x=0, y=1;
  while (x++ || y++);
  return 0;
}

Or, if you have a multi-core processor -- untested ... just like the one above :)

int main(void) {
#pragma omp parallel
  {
    volatile unsigned x=0, y=1;
    while (x++ || y++);
  }
  return 0;
}


What about this one:

int main() { for (;;); }


Here's a good, old-fashioned fork bomb.

#include <unistd.h>
int main(void)
{
  while(1)
    fork();
  return 0;
}


Copy and paste this in a file named source.c:

int main(int argc, char *argv) {
    while(1);
}

Compile source.c: gcc source.c -o myprogram

Run it: ./myprogram


The answers suggesting an empty loop shall only bring dual core CPU to 50%, quad-core to 25% etc.

So if that is an issue one can use something like

void main(void)
{
    omp_set_dynamic(0);
    // In most implemetations omp_get_num_procs() return #cores 
    omp_set_num_threads(omp_get_num_procs());
    #pragma omp parallel for
    for(;;) {}
}


Native Windows solution for multithreaded systems. Compiles on Visual C++ (or Visual Studio) without any library.

/* Use 100% CPU on multithreaded Windows systems */

#include <Windows.h>
#include <stdio.h>
#define NUM_THREADS 4

DWORD WINAPI mythread(__in LPVOID lpParameter)
{
    printf("Thread inside %d \n", GetCurrentThreadId());
    volatile unsigned x = 0, y = 1;
    while (x++ || y++);
    return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE handles[NUM_THREADS];
    DWORD mythreadid[NUM_THREADS];
    int i;

    for (i = 0; i < NUM_THREADS; i++)
    {
        handles[i] = CreateThread(0, 0, mythread, 0, 0, &mythreadid[i]);
        printf("Thread after %d \n", mythreadid[i]);
    }

    getchar();
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜