0
0

pythonでCPU100%

Last updated at Posted at 2023-12-18

シングルプロセス

import multiprocessing
import threading
import sys

def max_cpu_task():
    """ CPUを最大限に活用するための単純な無限ループ """
    while True:
        pass

def single_process():
    """ シングルプロセスでCPUを最大限に活用 """
    max_cpu_task()

def multi_process():
    """ マルチプロセスでCPUを最大限に活用 """
    processes = []
    for _ in range(multiprocessing.cpu_count()):
        p = multiprocessing.Process(target=max_cpu_task)
        p.start()
        processes.append(p)

    for p in processes:
        p.join()

def multi_threaded():
    """ シングルプロセス・マルチスレッドでCPUを最大限に活用 """
    threads = []
    for _ in range(threading.cpu_count()):
        t = threading.Thread(target=max_cpu_task)
        t.start()
        threads.append(t)

    for t in threads:
        t.join()

if __name__ == "__main__":
    if len(sys.argv) >= 2:
        mode = sys.argv[1]
        if mode == "single":
            print("シングルプロセスモードで実行します。")
            single_process()
        elif mode == "multi":
            print("マルチプロセスモードで実行します。")
            multi_process()
        elif mode == "thread":
            print("シングルプロセス・マルチスレッドモードで実行します。")
            multi_threaded()
        else:
            print("無効なモードが指定されました。'single', 'multi', または 'thread' のいずれかを指定してください。")
    else:
        print("モードが指定されていません。'single', 'multi', または 'thread' のいずれかを指定してください。")

C言語

#include <stdio.h>
#include <time.h>

int main() {
    long long count = 0;
    int sum = 0;
    time_t start, end;

    // 現在の時刻を取得
    time(&start);

    // 5秒間足し算を実行
    while (1) {
        sum += 1; // 何か単純な操作
        count++;

        // 現在の時刻を取得
        time(&end);

        // 5秒経過したらループを抜ける
        if (difftime(end, start) >= 5.0)
            break;
    }

    printf("Total iterations: %lld\n", count);

    return 0;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0