はじめに
このプログラムでは、NAND論理回路をJavaScript、Java、C、C++、Python、MyHDLの6言語で実装し、すべての入力組み合わせに対する出力と処理時間を比較します。言語ごとの特徴や速度の違いを可視化することが目的です。
実行Pythonコード
# 必要なモジュールのインポート (Import required modules)
!pip install myhdl
import subprocess # 他言語コードのコンパイル・実行に使用 / Used for running external commands
import time # 実行時間の計測 / Used to measure execution time
import os # ファイル操作などに使用 / For file operations
# NANDゲートの全ての入力組み合わせ / All possible input combinations for a NAND gate
inputs = [(0, 0), (0, 1), (1, 0), (1, 1)]
# --- 各言語でNANDゲートを実装するコードを保存 --- #
# JavaScriptコードを書き出す / Write JavaScript code to a file
with open("nand.js", "w") as f:
f.write('''const a = parseInt(process.argv[2]); const b = parseInt(process.argv[3]);
console.log(!(a && b) ? 1 : 0);''')
# Javaコードを書き出してコンパイル / Write Java code and compile it
with open("Nand.java", "w") as f:
f.write('''public class Nand {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println((a == 1 && b == 1) ? 0 : 1);
}
}''')
subprocess.run(["javac", "Nand.java"]) # Javaのコンパイル / Compile Java
# Cコードを書き出してコンパイル / Write and compile C code
with open("nand.c", "w") as f:
f.write('''#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int a = atoi(argv[1]), b = atoi(argv[2]);
printf("%d\\n", !(a && b));
return 0;
}''')
subprocess.run(["gcc", "nand.c", "-o", "nand"]) # Cのコンパイル / Compile C
# C++コードを書き出してコンパイル / Write and compile C++ code
with open("nand.cpp", "w") as f:
f.write('''#include <iostream>
#include <cstdlib>
int main(int argc, char* argv[]) {
int a = std::atoi(argv[1]), b = std::atoi(argv[2]);
std::cout << (!(a && b)) << std::endl;
return 0;
}''')
subprocess.run(["g++", "nand.cpp", "-o", "nandpp"]) # C++のコンパイル / Compile C++
# --- 汎用テスト関数:各言語でNANDを実行 --- #
def test_lang(name, cmd_builder):
"""
外部言語コードを使ってNANDの出力と実行時間を表示
Run and evaluate NAND logic from various languages.
"""
print(f"\n[{name}]")
start = time.time()
for a, b in inputs:
cmd = cmd_builder(a, b)
result = subprocess.run(cmd, capture_output=True, text=True)
print(f"{a} NAND {b} => {result.stdout.strip()}")
end = time.time()
print(f"Execution Time: {end - start:.4f} sec")
# --- PythonによるNAND計算 --- #
def test_python():
"""
PythonでNANDゲートを計算(シンプルな論理式) / Simulate NAND logic using pure Python.
"""
print("\n[Python]")
start = time.time()
for a, b in inputs:
result = 0 if a and b else 1
print(f"{a} NAND {b} => {result}")
end = time.time()
print(f"Execution Time: {end - start:.4f} sec")
# --- MyHDL(HDL記述でのNANDシミュレーション) --- #
def test_myhdl():
"""
MyHDLを使ってハードウェア記述でNANDゲートをシミュレーション
Simulate a NAND gate using MyHDL (Python-based HDL).
"""
print("\n[MyHDL]")
from myhdl import block, Signal, always_comb, instance, delay, Simulation
# NAND回路ブロックの定義 / Define the NAND gate logic
@block
def nand_gate(a, b, y):
@always_comb
def logic():
y.next = not (a and b) # NAND論理 / NAND logic
return logic
# テストベンチの定義 / Define the testbench
@block
def testbench():
a = Signal(bool(0))
b = Signal(bool(0))
y = Signal(bool(0))
nand = nand_gate(a, b, y)
@instance
def stimulus():
print("A B | A NAND B")
for av in (0, 1):
for bv in (0, 1):
a.next = av
b.next = bv
yield delay(1) # 時間遅延(1単位)/ Simulate 1 unit delay
print(f"{int(a)} {int(b)} | {int(y)}")
return nand, stimulus
start = time.time()
tb = testbench()
tb.run_sim() # シミュレーション実行 / Run the simulation
end = time.time()
print(f"Execution Time: {end - start:.4f} sec")
# --- 全言語でテスト実行 / Run all tests --- #
test_lang("JavaScript", lambda a, b: ["node", "nand.js", str(a), str(b)])
test_lang("Java", lambda a, b: ["java", "Nand", str(a), str(b)])
test_lang("C", lambda a, b: ["./nand", str(a), str(b)])
test_lang("C++", lambda a, b: ["./nandpp", str(a), str(b)])
test_python()
test_myhdl()
結果