因此,我编写了一个python和一个C程序来比较运行时,它们都将10 ^ 7字节写入同一文件。我希望C程序的时间短得多,但是我错了。
顺便说一句,运行C代码时,感觉比python代码要快。同时也为没有评论而感到抱歉,这是当下的一种精神,而且非常简单。
下面是两者的结果和代码,知道为什么会这样吗?
结果:
The c program took 4.410720e+05s
The python program took 2.296329s
C代码:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void program(){
FILE *f;
f = fopen("temp.txt", "w");
for(unsigned int i = 1; i <= pow(10,7); i++){
fprintf(f, "a");
}
fclose(f);
}
int main(void){
clock_t begin = clock();
program();
clock_t end = clock();
double time_spent = (double)(end - begin);
FILE *f = fopen("runtime_log","a");
fprintf(f, "The c program took ");
fprintf(f, "%les\n",time_spent);
fclose(f);
return 0;
}
Python代码:
import time
def main():
start = time.time()
program()
end = time.time()
runtime = end - start
f = open('runtime_log','a')
f.write('The python program took %fs\n' %runtime)
def program():
f = open('temp.txt','w')
for i in range(10**7):
f.write('a')
main()
答案 0 :(得分:1)
代替此:
fprintf(f, "%les\n",time_spent);
尝试一下:
fprintf(f, "%les\n",time_spent/CLOCKS_PER_SEC);
您的结果有误的原因是因为您假设这将是秒,但实际上它们是未公开的时间单位,因此您需要除以CLOCKS_PER_SEC
才能获得秒数。