2
2

Pythonコードからサブプロセスを使用して、超高速なC++プログラムをコンパイルして実行します。マシン性能の限界を引き出します。

Last updated at Posted at 2024-07-19

5e65959b-400b-4530-b1c3-f0e899bb0c53.png

それぞれのC++コードの計算内容に基づいたテーマのショートストーリーを紹介します。

  1. Hello World
    テーマ: 初めての冒険

ジョンはプログラミングの世界に足を踏み入れたばかりの若者だった。彼は「Hello, World!」とコンピュータに向かって叫び、それが新しい冒険の始まりだと感じた。この一言は、彼に無限の可能性を感じさせ、次のステップへと導いた。

  1. 基本的な四則演算
    テーマ: 商店の計算

メアリーは小さな町の商店を経営していた。ある日、彼女は売り上げを計算しながら、お客さんたちと親しく会話をしていた。「今日の売り上げは...」彼女は計算し始めた。「5ドルのリンゴが10個、10ドルのオレンジが5個、掛け算して、足し算して...これで一日の終わりには家計簿もぴったりね!」

  1. 条件分岐
    テーマ: 運命の選択

エマは人生の重要な選択を前に立ち止まった。大学に進むべきか、それとも家業を継ぐべきか。「もし大学に行けば、新しい知識と出会いが待っている。でも、家業を継げば家族を支えることができる。」彼女は自問自答しながら、未来を見つめていた。

  1. ループ
    テーマ: 日々の訓練

アレックスはランナーで、毎朝5周のトラックを走ることを日課にしていた。「1周目...2周目...まだまだだ!」彼は自分自身に言い聞かせながら、毎日の訓練を繰り返した。彼の目標は来月のマラソン大会で優勝することだった。

  1. 関数
    テーマ: 友情の力

リサとマイクは親友で、いつも一緒に遊んでいた。ある日、リサは新しいゲームを考え出し、それをマイクに教えた。「このゲームでは、2つの数を足して、その結果を使って次のステップに進むんだよ!」彼らは楽しみながら、新しい遊び方を発見していった。

  1. 配列
    テーマ: 家族の思い出

トムは古いアルバムを開いて、家族の写真を見返していた。「これが僕の家族だ。1枚目は僕が生まれたとき、2枚目は初めての家族旅行、3枚目は僕の卒業式...」彼はそれぞれの写真を見ながら、過去の思い出に浸っていた。

  1. ポインタ
    テーマ: 探偵の手がかり

探偵ジョーは重要な手がかりを見つけた。彼はその手がかりを基に、次の行動を決めなければならなかった。「この指紋はどこへ繋がっているんだ?」彼は手がかりのポイントを追いながら、真実に近づいていった。

  1. クラスとオブジェクト
    テーマ: 新しい出会い

アンは新しい町に引っ越してきたばかりだった。彼女はそこで新しい友人たちに出会った。「こんにちは、私の名前はアン。よろしくね!」彼女は自己紹介をし、新しい環境での生活を楽しみ始めた。

  1. 継承
    テーマ: 家族の絆

ケイトは家族から多くのことを学んだ。彼女の母親は料理の達人で、父親は優れた大工だった。「私は母から料理の技を、父から工作の技術を受け継いだの。」彼女は自分が家族の一員であることを誇りに思い、それを次世代に伝えることを決意した。

  1. ファイル操作
    テーマ: 手紙の記憶

サラは古い手紙を整理していた。彼女はその中の一通に目を留めた。「この手紙は、私が初めて遠くの友達に送った手紙だわ。」彼女は手紙を読み返し、その時の思い出が鮮明に蘇った。手紙の内容は大切な記憶の一部であり、それを大切に保管することにした。

これらのショートストーリーは、それぞれのC++コードの計算内容をテーマにしています。各ストーリーは、日常の一コマや特別な出来事を描いており、プログラミングの概念を学ぶ楽しさを伝えることを目的としています。

Pythonのサブプロセスを使用して、10個の異なるC++プログラムをコンパイルして実行します。各プログラムの出力はコンソールに表示されます。

Pythonコードから、超高速なC++プログラムをコンパイルして実行します。

実行結果。

Output of program_1:
Hello, World!

Output of program_2:
Addition: 15
Subtraction: -5
Multiplication: 50
Division: 0

Output of program_3:
a is less than b

Output of program_4:
i: 0
i: 1
i: 2
i: 3
i: 4

Output of program_5:
Result: 15

Output of program_6:
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4
arr[4]: 5

Output of program_7:
Value of a: 5
Address of a: 0x7fffee44c57c
Pointer p points to: 0x7fffee44c57c
Value pointed to by p: 5

Output of program_8:
Name: John, Age: 30

Output of program_9:
Eating...
Barking...

Output of program_10:
This is a line.

Pythonコード

以下のPythonコードは、上記のC++コードをコンパイルして実行する方法を示しています。

Google Colabでの実行手順

Google Colabにアクセスし、新しいPythonノートブックを作成します。
上記のPythonスクリプトをノートブックのセルにコピー&ペーストします。
セルを実行して、各C++コードの実行結果を確認します。
このスクリプトは、10個の異なるC++プログラムをファイルに保存し、それぞれをコンパイルして実行します。各プログラムの出力はPythonのサブプロセスを使用して取得され、コンソールに表示されます。


import subprocess

# C++コードをファイルに保存する関数
def save_cpp_code(filename, code):
    with open(filename, 'w') as file:
        file.write(code)

# C++コードをコンパイルする関数
def compile_cpp_code(filename, output):
    try:
        subprocess.run(["g++", "-o", output, filename], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Error in compilation of {filename}: {e}")
        print("Output:", e.output)
        print("Error output:", e.stderr)

# C++コードを実行する関数
def run_cpp_code(executable):
    try:
        result = subprocess.run([f"./{executable}"], check=True, capture_output=True, text=True)
        print(f"Output of {executable}:")
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"Error in execution of {executable}: {e}")
        print("Output:", e.output)
        print("Error output:", e.stderr)

# C++コードのリスト
cpp_codes = [
    ("hello_world.cpp", """
    #include <iostream>
    using namespace std;

    int main() {
        cout << "Hello, World!" << endl;
        return 0;
    }
    """),
    ("basic_arithmetic.cpp", """
    #include <iostream>
    using namespace std;

    int main() {
        int a = 5, b = 10;
        cout << "Addition: " << a + b << endl;
        cout << "Subtraction: " << a - b << endl;
        cout << "Multiplication: " << a * b << endl;
        cout << "Division: " << a / b << endl;
        return 0;
    }
    """),
    ("conditional.cpp", """
    #include <iostream>
    using namespace std;

    int main() {
        int a = 5, b = 10;
        if (a < b) {
            cout << "a is less than b" << endl;
        } else {
            cout << "a is not less than b" << endl;
        }
        return 0;
    }
    """),
    ("loop.cpp", """
    #include <iostream>
    using namespace std;

    int main() {
        for (int i = 0; i < 5; i++) {
            cout << "i: " << i << endl;
        }
        return 0;
    }
    """),
    ("function.cpp", """
    #include <iostream>
    using namespace std;

    int add(int a, int b) {
        return a + b;
    }

    int main() {
        int result = add(5, 10);
        cout << "Result: " << result << endl;
        return 0;
    }
    """),
    ("array.cpp", """
    #include <iostream>
    using namespace std;

    int main() {
        int arr[5] = {1, 2, 3, 4, 5};
        for (int i = 0; i < 5; i++) {
            cout << "arr[" << i << "]: " << arr[i] << endl;
        }
        return 0;
    }
    """),
    ("pointer.cpp", """
    #include <iostream>
    using namespace std;

    int main() {
        int a = 5;
        int *p = &a;
        cout << "Value of a: " << a << endl;
        cout << "Address of a: " << &a << endl;
        cout << "Pointer p points to: " << p << endl;
        cout << "Value pointed to by p: " << *p << endl;
        return 0;
    }
    """),
    ("class.cpp", """
    #include <iostream>
    using namespace std;

    class Person {
    public:
        string name;
        int age;
        
        void introduce() {
            cout << "Name: " << name << ", Age: " << age << endl;
        }
    };

    int main() {
        Person p;
        p.name = "John";
        p.age = 30;
        p.introduce();
        return 0;
    }
    """),
    ("inheritance.cpp", """
    #include <iostream>
    using namespace std;

    class Animal {
    public:
        void eat() {
            cout << "Eating..." << endl;
        }
    };

    class Dog : public Animal {
    public:
        void bark() {
            cout << "Barking..." << endl;
        }
    };

    int main() {
        Dog d;
        d.eat();
        d.bark();
        return 0;
    }
    """),
    ("file_io.cpp", """
    #include <iostream>
    #include <fstream>
    using namespace std;

    int main() {
        ofstream outfile("example.txt");
        outfile << "This is a line." << endl;
        outfile.close();

        ifstream infile("example.txt");
        string line;
        while (getline(infile, line)) {
            cout << line << endl;
        }
        infile.close();
        return 0;
    }
    """)
]

# 各C++コードを処理する
for i, (filename, code) in enumerate(cpp_codes):
    executable = f"program_{i+1}"
    save_cpp_code(filename, code)
    compile_cpp_code(filename, executable)
    run_cpp_code(executable)

Google Colabでの実行手順
Google Colabにアクセスし、新しいPythonノートブックを作成します。
上記のPythonスクリプトをノートブックのセルにコピー&ペーストします。
セルを実行して、各C++コードの実行結果を確認します。
このスクリプトは、10個の異なるC++プログラムをファイルに保存し、それぞれをコンパイルして実行します。各プログラムの出力はPythonのサブプロセスを使用して取得され、コンソールに表示されます。

2
2
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
2
2