因为这周作业里有对比算法计算效率的要求,找了很久没有找到C++有合适的程序或插件,索性让ai给写了一个python脚本,经过调整得到合适的
我需要的:

  1. 对比输出 爬山法可能无法得到全部解 我希望看到它能够算出多少的解,和实际解的区别
  2. 输出运行时间
import subprocess
import matplotlib.pyplot as plt
import numpy as np
import os
from time import sleep
import matplotlib
import time

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

def run_exe_with_input(exe_path, input_value, timeout=10):
    """运行.exe程序并传入输入值,返回输出结果和运行时间(ms)"""
    try:
        start_time = time.time()  # 记录开始时间
        
        process = subprocess.Popen(
            exe_path,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        stdout, stderr = process.communicate(input=str(input_value), timeout=timeout)
        
        end_time = time.time()  # 记录结束时间
        execution_time = (end_time - start_time) * 1000  # 转换为毫秒
        
        output = stdout.strip()
        try:
            return float(output), execution_time
        except ValueError:
            import re
            numbers = re.findall(r"[-+]?\d*\.\d+|\d+", output)
            return (float(numbers[0]) if numbers else 0), execution_time
                
    except Exception as e:
        print(f"运行出错 (输入: {input_value}): {e}")
        return 0, 0

def main():
    exe_path = "climb.exe"  # 替换为你的.exe文件路径
    exe_std_path = "eightqueen.exe"
    inputs = list(range(1, 14))
    outputs = []
    outputs2 = []
    execution_times = []  # 存储climb.exe的运行时间
    execution_times2 = []  # 存储eightqueen.exe的运行时间
    
    if not os.path.exists(exe_path):
        print(f"错误: 找不到文件 {exe_path}")
        return
    
    if not os.path.exists(exe_std_path):
        print(f"错误: 找不到文件 {exe_std_path}")
        return
    
    print("开始分析程序 climb.exe...")
    
    # 收集climb.exe数据
    for input_val in inputs:
        print(f"climb输入: {input_val:2d} -> ", end="", flush=True)
        output, exec_time = run_exe_with_input(exe_path, input_val)
        outputs.append(output)
        execution_times.append(exec_time)
        print(f"输出: {output}, 时间: {exec_time:.2f}ms")
        sleep(0.05)

    print("\n开始分析程序 eightqueen.exe...")
    
    # 收集eightqueen.exe数据
    for input_val in inputs:
        print(f"std输入: {input_val:2d} -> ", end="", flush=True)
        output2, exec_time2 = run_exe_with_input(exe_std_path, input_val)
        outputs2.append(output2)
        execution_times2.append(exec_time2)
        print(f"std输出: {output2}, 时间: {exec_time2:.2f}ms")
        sleep(0.05)
    
    # 创建3x2的子图布局
    fig, axes = plt.subplots(3, 2, figsize=(16, 12))
    
    # 第一行: climb.exe 的输出结果和分布
    ax1, ax2 = axes[0]
    
    # climb.exe 折线图
    ax1.plot(inputs, outputs, 'bo-', linewidth=2, markersize=8, label='climb.exe输出')
    ax1.set_xlabel('输入值', fontsize=12)
    ax1.set_ylabel('输出值', fontsize=12)
    ax1.set_title('climb.exe 输入输出关系图', fontsize=14)
    ax1.grid(True, alpha=0.3)
    ax1.legend()
    
    # 添加数据标签
    for i, (x, y) in enumerate(zip(inputs, outputs)):
        ax1.annotate(f'{y}', (x, y), textcoords="offset points", 
                    xytext=(0,10), ha='center', fontsize=9)
    
    # climb.exe 柱状图
    ax2.bar(inputs, outputs, alpha=0.7, color='lightcoral')
    ax2.set_xlabel('输入值', fontsize=12)
    ax2.set_ylabel('输出值', fontsize=12)
    ax2.set_title('climb.exe 输出值分布', fontsize=14)
    ax2.grid(True, alpha=0.3)

    for i, v in enumerate(outputs):
        ax2.text(i + 1, v, f'{v}', ha='center', va='bottom', fontsize=9)
    
    # 第二行: eightqueen.exe 的输出结果和分布
    ax3, ax4 = axes[1]
    
    # eightqueen.exe 折线图
    ax3.plot(inputs, outputs2, 'go-', linewidth=2, markersize=8, label='eightqueen.exe输出')
    ax3.set_xlabel('输入值', fontsize=12)
    ax3.set_ylabel('输出值', fontsize=12)
    ax3.set_title('eightqueen.exe 输入输出关系图', fontsize=14)
    ax3.grid(True, alpha=0.3)
    ax3.legend()
    
    # 添加数据标签
    for i, (x, y) in enumerate(zip(inputs, outputs2)):
        ax3.annotate(f'{y}', (x, y), textcoords="offset points", 
                    xytext=(0,10), ha='center', fontsize=9)
    
    # eightqueen.exe 柱状图
    ax4.bar(inputs, outputs2, alpha=0.7, color='lightgreen')
    ax4.set_xlabel('输入值', fontsize=12)
    ax4.set_ylabel('输出值', fontsize=12)
    ax4.set_title('eightqueen.exe 输出值分布', fontsize=14)
    ax4.grid(True, alpha=0.3)

    for i, v in enumerate(outputs2):
        ax4.text(i + 1, v, f'{v}', ha='center', va='bottom', fontsize=9)
    
    # 第三行: 运行时间对比
    ax5, ax6 = axes[2]
    
    # 运行时间折线图对比
    ax5.plot(inputs, execution_times, 'ro-', linewidth=2, markersize=8, label='climb.exe运行时间')
    ax5.plot(inputs, execution_times2, 'bo-', linewidth=2, markersize=8, label='eightqueen.exe运行时间')
    ax5.set_xlabel('输入值', fontsize=12)
    ax5.set_ylabel('运行时间 (ms)', fontsize=12)
    ax5.set_title('两个程序运行时间对比', fontsize=14)
    ax5.grid(True, alpha=0.3)
    ax5.legend()
    
    # 添加时间数据标签
    for i, (x, y) in enumerate(zip(inputs, execution_times)):
        ax5.annotate(f'{y:.1f}ms', (x, y), textcoords="offset points", 
                    xytext=(0,10), ha='center', fontsize=8)
    for i, (x, y) in enumerate(zip(inputs, execution_times2)):
        ax5.annotate(f'{y:.1f}ms', (x, y), textcoords="offset points", 
                    xytext=(0,-15), ha='center', fontsize=8)
    
    # 运行时间柱状图对比
    bar_width = 0.35
    x_index = np.arange(len(inputs))
    
    ax6.bar(x_index - bar_width/2, execution_times, bar_width, 
             alpha=0.7, color='red', label='climb.exe')
    ax6.bar(x_index + bar_width/2, execution_times2, bar_width, 
             alpha=0.7, color='blue', label='eightqueen.exe')
    ax6.set_xlabel('输入值', fontsize=12)
    ax6.set_ylabel('运行时间 (ms)', fontsize=12)
    ax6.set_title('运行时间分布对比', fontsize=14)
    ax6.set_xticks(x_index)
    ax6.set_xticklabels(inputs)
    ax6.grid(True, alpha=0.3)
    ax6.legend()
    
    # 在柱状图上添加时间数值
    for i, v in enumerate(execution_times):
        ax6.text(i - bar_width/2, v, f'{v:.1f}ms', ha='center', va='bottom', fontsize=7)
    for i, v in enumerate(execution_times2):
        ax6.text(i + bar_width/2, v, f'{v:.1f}ms', ha='center', va='bottom', fontsize=7)
    
    plt.tight_layout()
    plt.show()
    
    # 打印统计信息
    print("\n" + "="*50)
    print("运行时间统计摘要:")
    print(f"climb.exe - 平均时间: {np.mean(execution_times):.2f}ms, 最大时间: {np.max(execution_times):.2f}ms, 最小时间: {np.min(execution_times):.2f}ms")
    print(f"eightqueen.exe - 平均时间: {np.mean(execution_times2):.2f}ms, 最大时间: {np.max(execution_times2):.2f}ms, 最小时间: {np.min(execution_times2):.2f}ms")
    print("="*50)

if __name__ == "__main__":
    main()

在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐