gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:26 25 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 使用 Python 脚本在 C 代码中添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com