Python运行时与C运行时
所以我编写了一个python和一个C程序来比较运行时,它们都向同一个文件写入10^7字节。我原以为C程序的时间会短得多,但我错了 顺便说一句,运行C代码时,感觉比python代码快。对于没有评论也很抱歉,这是一种当下精神,非常简单 下面是两者的结果和代码,知道为什么会发生这种情况吗 结果:Python运行时与C运行时,python,c,runtime,Python,C,Runtime,所以我编写了一个python和一个C程序来比较运行时,它们都向同一个文件写入10^7字节。我原以为C程序的时间会短得多,但我错了 顺便说一句,运行C代码时,感觉比python代码快。对于没有评论也很抱歉,这是一种当下精神,非常简单 下面是两者的结果和代码,知道为什么会发生这种情况吗 结果: The c program took 4.410720e+05s The python program took 2.296329s C代码: #include <time.h> #includ
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;
}
与此相反:
fprintf(f, "%les\n",time_spent);
试试这个:
fprintf(f, "%les\n",time_spent/CLOCKS_PER_SEC);
你的结果是错误的原因是因为你假设它是秒,但它们实际上是一个未公开的时间单位,你需要除以
时钟每秒
来获得秒数。你在构建C程序时启用了优化吗?否则会多次调用浮点函数pow
,这当然会影响执行时间。clock()
不会返回秒,请阅读手册页。(由于您的代码只执行I/O操作,因此没有理由一种语言比另一种语言快,您测试操作系统的时间比其他任何语言都长。)请使用重试(unsigned int I=0;I<10000000;I++)fputc('a',f)代码>440000s约为5天!您是否等待了5天C程序终止??哇!
fprintf(f, "%les\n",time_spent/CLOCKS_PER_SEC);