Ubuntu20.04下GDB10.2如何配置std::chrono duration类型的美化打印
std::chrono::duration GDB Pretty Printer 实现方案
你使用的GDB 10.2版本自带的libstdc++ pretty printer暂未覆盖std::chrono::duration类型,可以使用以下自定义Python实现直接添加支持:
实现代码
import gdb.printing class ChronoDurationPrinter: """Pretty printer for std::chrono::duration""" def __init__(self, val): self.val = val self.rep_val = val['__r'] ratio_type = val.type.template_argument(1) self.ratio_num = int(ratio_type.template_argument(0)) self.ratio_den = int(ratio_type.template_argument(1)) def to_string(self): count = int(self.rep_val) sec_total = count * self.ratio_num / self.ratio_den # 匹配常用时间单位 unit_map = [ (3600, "h"), (60, "min"), (1, "s"), (1e-3, "ms"), (1e-6, "µs"), (1e-9, "ns"), (1e-12, "ps") ] for factor, unit in unit_map: if abs(sec_total) >= factor or factor == 1e-12: scaled_val = sec_total / factor if scaled_val.is_integer(): scaled_val = int(scaled_val) return f"{scaled_val}{unit}" return f"{count} [custom duration <{self.ratio_num}/{self.ratio_den}>]" def register_chrono_printers(): pp = gdb.printing.RegexpCollectionPrettyPrinter("std_chrono") pp.add_printer("std::chrono::duration", r"^std::chrono::duration<.*>$", ChronoDurationPrinter) gdb.printing.register_pretty_printer(gdb.current_objfile(), pp, replace=True) register_chrono_printers()
部署方式
- 将上述代码保存为
gdb_chrono_printer.py,存放至用户根目录(~/) - 打开用户根目录下的
.gdbinit文件,末尾添加如下内容:
注意替换路径中的用户名为实际系统用户名python import sys sys.path.insert(0, "/home/你的用户名/") import gdb_chrono_printer end - 重启GDB或CLion即可生效,打印
std::chrono::duration类型变量时会直接输出133ns这类直观格式
兼容说明
- 支持所有基于libstdc++实现的
std::chrono::duration变体,包括自定义比例的duration类型 - 完全兼容CLion的GDB调试场景,无需额外修改IDE配置
内容的提问来源于stack exchange,提问作者gg99
相关产品推荐
相关产品推荐

