You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gnuplot如何使用字符索引数组存储多文件CPU时间统计最大值

问题原因

gnuplot 传统固定长度数组仅支持整数类型索引,你代码中用字符串'a'/'b'作为下标访问数组时,程序无法识别对应位置,因此触发索引越界错误。

解决方案

根据你使用的gnuplot版本,选对应方案即可:

方案1:gnuplot 5.4及以上版本(推荐)

gnuplot从5.4版本开始原生支持关联数组(即字符串键值的数组),只需要修改数组声明方式即可,其余逻辑几乎不用改动:

  • 将原代码中array tmax[5]替换为array tmax[],空方括号表示声明一个不限长度、支持任意类型键的关联数组
  • 给stats命令添加nooutput参数,避免每次统计都在控制台输出冗余的统计信息
  • 由于你的y轴标注是归一化百分比,绘图时需要将归一化结果乘100,和单位匹配
    修改后的完整可运行代码如下:
#!/usr/bin/gnuplot

set style data histogram
set style fill solid
set style histogram clustered
set xtics rotate by 45 offset 0,0 right
set lmargin  8
set bmargin 11

# border
set style line 11 lc rgb '#808080' lt 1
set border 3 back ls 11
set tics nomirror

# grid
set style line 12 lc rgb '#808080' lt 0 lw 1
set grid back ls 12

set terminal postscript eps size 3.5,2.62 enhanced color \
    font 'Helvetica, 10' linewidth 1

set output 'advisor.eps'
set xlabel 'C++ function'
set ylabel 't_{cpu} norm, %'

# 声明支持字符串索引的关联数组
array tmax[]

# 统计并存储每个文件的CPU耗时最大值
do for [l in "a b c d e"] {
    fname = sprintf('%s.txt', l)
    stats fname using 2 nooutput
    tmax[l] = STATS_max
}

# 打印校验最大值
do for [l in "a b c d e"] {
    print l, tmax[l]
}

plot "a.txt" using ($2/tmax['a']*100):xtic(1) title 'p=1, t=1', \
     "b.txt" using ($2/tmax['b']*100)         title 'p=1, t=8', \
     "c.txt" using ($2/tmax['c']*100)         title 'p=8, t=1', \
     "d.txt" using ($2/tmax['d']*100)         title 'p=4, t=2', \
     "e.txt" using ($2/tmax['e']*100)         title 'p=2, t=4'

方案2:兼容gnuplot 5.4以下旧版本

如果你的环境中gnuplot版本低于5.4,没有关联数组特性,可以通过动态变量名拼接的方式实现相同效果,不需要预先定义数组:

  1. 统计最大值时,用eval动态生成带文件标识的独立变量存储结果:
do for [l in "a b c d e"] {
    fname = sprintf('%s.txt', l)
    stats fname using 2 nooutput
    eval(sprintf("tmax_%s = %f", l, STATS_max))
}
  1. 取值时用value()函数传入对应变量名字符串获取数值即可,绘图部分修改为:
plot "a.txt" using ($2/value('tmax_a')*100):xtic(1) title 'p=1, t=1', \
     "b.txt" using ($2/value('tmax_b')*100)         title 'p=1, t=8', \
     "c.txt" using ($2/value('tmax_c')*100)         title 'p=8, t=1', \
     "d.txt" using ($2/value('tmax_d')*100)         title 'p=4, t=2', \
     "e.txt" using ($2/value('tmax_e')*100)         title 'p=2, t=4'

其余绘图配置代码不需要改动。

内容的提问来源于stack exchange,提问作者mabalenk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 00:51:21