为什么 PyYAML 花费这么多时间来解析 YAML 文件?

2024-05-18

我正在解析一个大约 6500 行的 YAML 文件,格式如下:

foo1:
  bar1:
    blah: { name: "john", age: 123 }
  metadata: { whatever1: "whatever", whatever2: "whatever" }
  stuff:
    thing1: 
      bluh1: { name: "Doe1", age: 123 }
      bluh2: { name: "Doe2", age: 123 }
    thing2:
    ...
    thingN:
foo2:
...
fooN:

我只想用PyYAML 库 http://pyyaml.org/(我认为Python中没有更多的替代方案:如何在 Python 中解析 YAML 文件 https://stackoverflow.com/questions/1773805/best-way-to-parse-a-yaml-file).

只是为了测试,我编写了代码来解析我的文件:

import yaml

config_file = "/path/to/file.yaml"

stream = open(config_file, "r")
sensors = yaml.load(stream)

执行脚本time命令以及我这次得到的脚本:

real    0m3.906s
user    0m3.672s
sys     0m0.100s

这个价值观看起来确实不太好。我只想用 JSON 进行相同的测试,只需首先将相同的 YAML 文件转换为 JSON:

import json

config_file = "/path/to/file.json"

stream = open(config_file, "r")
sensors = json.load(stream)  # We read the yaml config file

但执行时间要好得多:

real    0m0.058s
user    0m0.032s
sys     0m0.008s

为什么 PyYAML 花费更多时间解析 YAML 文件而不是解析 JSON 文件的主要原因?是PyYAML的问题还是因为YAML格式很难解析?(可能是第一个)

EDIT:

我使用 ruby​​ 和 YAML 添加另一个示例:

require 'yaml'

sensors = YAML.load_file('/path/to/file.yaml')

而且执行时间也不错! (或者至少不像 PyYAML 示例那么糟糕):

real    0m0.278s
user    0m0.240s
sys     0m0.032s

根据the docs http://pyyaml.org/wiki/PyYAMLDocumentation你必须使用CLoader/CSafeLoader (and CDumper):

import yaml
try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

config_file = "test.yaml"

stream = open(config_file, "r")
sensors = yaml.load(stream, Loader=Loader)

这给了我

real    0m0.503s

代替

real    0m2.714s
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 PyYAML 花费这么多时间来解析 YAML 文件? 的相关文章

随机推荐