2

我需要计算 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;
}
4

2 回答 2

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
于 2013-07-17T01:57:23.767 回答
-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用显式的字符串解析代码替换调用;它会更冗长一些。

于 2013-07-17T01:28:43.493 回答