Ruby - GCC的依赖文件解析优化

时间:2011-12-02 09:00:22

标签: ruby parsing gcc

我正在寻找关于用Ruby编写的下面代码的优化思路。它在依赖项文件中查找头文件依赖项(由GCC使用gcc -M -MM -MF生成)

我已经运行了Ruby分析器,发现大部分CPU时间花在了Array#下面的每个函数上。

lines = File.readlines(depends_file)
lines.each do |line|
  if line.include?(".h") then
    line.lstrip.rstrip.chomp("\\").split(' ').each do |line|
      header_dependencies << line
    end
  end
end

depends文件包含gcc -M选项指定的makefile规则格式的依赖项,请参阅GCC's Preprocessor Options。这是我项目中的一个例子 -

CyclicRedundancyCheck.o: src/CyclicRedundancyCheck.c \
 inc/CyclicRedundancyCheck.h inc/StdDefs.h

有人可以发布备用的,经过大量优化的解决方案吗?

2 个答案:

答案 0 :(得分:2)

没有经过大量优化但在这里更快一点(我的测试用例约为20%):

File.open(depends_file, 'r') do | io |
  io.each do |line|
    next unless line.include?('.h')
    header_dependencies.concat(line.split)
  end
end
header_dependencies.delete('\\')

我不认为你可以用Ruby本身获得更多。如果这太慢了,你应该考虑用C语言(部分)编程(作为扩展名)。

另请注意,该方法远非强大。 E.g。

 foo.o: src/ext.hlib/foo.c \

将错误地匹配。但是,使其更加强大,最有可能是性价比。

答案 1 :(得分:0)

基于Regex的解决方案比@ undur_gongor的解决方案更快(约5%)。

header_dependencies = Set.new
lines = File.readlines(depends_file)
lines.each do |line|
  header = line.match('[\w\/-]+\.h')
  header_dependencies.add(header.to_s) unless header.nil?
end

它遇到了与@undur_gongor提到的相同的缺陷,但这是我可以忍受的东西。