使用Python脚本在C代码中添加行

时间:2013-07-17 01:14:33

标签: python c

我需要计算C代码中循环的执行时间,为此我需要编写一个python脚本,通过检测循环之前和之后的注释来在循环之前和之后添加“gettimeofday”。

以下是代码:

int main(int argc, char** argv) {
  int i,j;
  int M = argv[0][0] * 10000;
  int res = argc; 

  // loopId = 1; depth = 1; outermost
  for (i=0; i<M; i++) {
    // loopId = 2; depth = 2; innermost 
    for (j=0; j<M; j++) {
      res *= 7 % 71;
    }     
    // end loop (loopId = 2)
    // loopId = 3; depth = 2; innermost
    for (j=0; j<M; j++){ 
      res += 9 % 91;
    }
    // end loop (loopId = 3)
  }
  // end loop (loopId = 1)

  return res;
}

2 个答案:

答案 0 :(得分:1)

import sys, re

expS=re.compile(r'\s*//\s*loopId = (\d+); depth = \d+; \w+')
expE=re.compile(r'\s*//\s*end loop \(loopId = (\d+)\)')
lines, varcnt = [], 0
with open(sys.argv[1]) as f:
    for line in f:
        line = line.rstrip()
        lines += [ line ]
        m = re.match(expS, line)
        if m:
            varcnt += 1
            loopid = int(m.group(1))
            lines += [ 'gettimeofday(&tv[{}], 0);'.format((loopid-1)*2) ]
            continue
        m = re.match(expE, line)
        if m:
            loopid = int(m.group(1))
            sid, eid = (loopid-1)*2, (loopid-1)*2+1
            lines += [ 'gettimeofday(&tv[{}], 0);'.format(eid) ]
            lines += [ 'printf("Id {}: %ld\\n", tdiff_xxx(&tv[{}],&tv[{}]));'.format(
                loopid, sid, eid) ]

print '#include <sys/time.h>'
print 'struct timeval tv[{}];'.format(varcnt*2)
print 'long tdiff_xxx(struct timeval *t0, struct timeval *t1) {'
print '  return (t1->tv_sec-t0->tv_sec)*1000000 + t1->tv_usec-t0->tv_usec;'
print '}' 
for l in lines: print l

答案 1 :(得分:-1)

任何代码转换工具的基本思路都很简单:

逐行迭代源(或者通过令牌或任何适当的迭代 - 但是给定样本,行是正常的)。将这些行复制到一个新文件中,同时添加添加的新行,并跟踪以后需要的任何信息。

这是使用的骨架:

rloop = re.compile(r'…')
rendloop = re.compile(r'…')

with open('old.c') as oldc, open('new.c', 'w') as newc:
    loops = {}
    for line in c:
        mloop = rloop.match(line.strip())
        if mloop:
            loops[m.groups(1)] = m.groups()
            newc.write(appropriate start-of-loop code)
        newc.write(line)
        mendloop = rendloop.match(line.strip())
        if mendloop:
            matching_start = loops[m.groups(1)]
            newc.write(appropriate end-of-loop code)

这应该足以让你入门。如果您有具体问题,请尽可能做,并提出具体问题。

如果您不知道如何使用正则表达式,可以使用显式字符串解析代码替换rloop.match调用;它会变得更加冗长。