Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Pythonで爆速でHello, World!する

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.

Pythonで爆速でHello, World!する

Avatar for AnaTofuZ

AnaTofuZ

May 24, 2025
Tweet

More Decks by AnaTofuZ

Other Decks in Technology

Transcript

  1. Houtou.pm 来週のこの時間!! きてくれ!! サーバーレス使わずにVPS とCDN でアプリ組んだ場合のモダンな 構成について話します “ “ #houtoupm

    では、純粋関数とワークフローオートメーションの蜜 月についてトークする予定です “ “ 3
  2. Hello, World まで 字句解析 print , Hello,World などのトークンに分解 構文解析 トークンの並びをPython

    で意味があるデータに変換 実行 PythonVM が構文解析のデータを元に命令を実行 字句解析 構⽂解析 VMが実⾏ Hello, World! 9
  3. Python の内部処理 print("Hello, World") は実際はこんな感じのPythonVM の命令にな る ❯ python -m

    dis hello.py 0 0 RESUME 0 1 2 PUSH_NULL 4 LOAD_NAME 0 (print) 6 LOAD_CONST 0 ('Hello, world!') 8 CALL 1 16 POP_TOP 18 RETURN_CONST 1 (None) 10
  4. 改めて処理を確認すると いわゆる python のCPython は全部分がC で書かれている つまりPython のコードは実際はC で書ける Hello,

    World! するだけなら別に構文解析とかする必要もない オブジェクトを作ってprint すればいいだけなので、PythonVM の 命令も短縮できるのでは 11
  5. 爆速Hello, World! 専用Python を作る 1. https://github.com/python/cpython を git clone 2.

    パッチを書く 3. ./configure デバッグしたいなら ./configure CFLAGS="-O0 -g" あたり 4. make -j 5. ./python して Hello, World! が出れば勝ち 13
  6. 起動時の状態で処理を切り分けている箇所にパッチをいれる static void pymain_run_python(int *exitcode) { ... pymain_header(config); _PyInterpreterState_SetRunningMain(interp); assert(!PyErr_Occurred());

    if (config->run_command) { *exitcode = pymain_run_command(config->run_command); } else if (config->run_module) { *exitcode = pymain_run_module(config->run_module, 1); } else if (main_importer_path != NULL) { *exitcode = pymain_run_module(L"__main__", 0); } else if (config->run_filename != NULL) { *exitcode = pymain_run_file(config); } else { *exitcode = pymain_run_stdin(config); } pymain_repl(config, exitcode); goto done; 14
  7. PyObject を書き込む PyObject_Print でC のファイルポインタにオブジェクトの内容を書 き込める stdout を指定してあげると print っぽくなる

    int res = PyObject_Print(py_str, stdout, Py_PRINT_RAW); if (res < 0) { PyErr_Print(); goto error; } Py_DECREF(py_str); Py_Finalize(); 16
  8. Python のI/O システムを使わずにstdout に書き込んでいる print 関数を厳密にエミュレートする場合は PyFile_WriteObject などのAPI でstdout に書き込むとよい

    PyObject *sys_module = PyImport_ImportModule("sys"); if (sys_module == NULL) { goto error; } PyObject *stdout_obj = PyObject_GetAttrString(sys_module, "stdout"); if (stdout_obj == NULL) { ... goto error; } PyFile_WriteObject(py_str, stdout_obj, Py_PRINT_RAW); 17
  9. ビルドすると... ❯ ./python Python 3.15.0a0 (heads/shingenpy-dirty:557ea496425, Jan 1 1980, 00:00:00)

    [GCC 14.2.1 20250322] on linux Type "help", "copyright", "credits" or "license" for more information. Hello, World! 無事Hello,World! がでた!!! 18