测试C语言中打印一句 hello world需要耗费多少时间
这次继续深入探究一下执行不同语句的耗时情况。
在我们的代码中,存在的比较典型的代码语句包括,算术运算,循环,逻辑判断,函数调用,打印,文件IO等。下面我们就测试一下这些语句在我电脑编译环境下的耗时情况。(注意不同的编译器和硬件配置会有不同的结果)
整型加和减:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
clock\_t begin, end;
double cost;
//开始记录
begin = clock();
/\*待测试程序段\*/
int a = 1;
for (int i = 0; i < 100000000; i++) {
a = a + 1;//a = a - 1;
}
//结束记录
end = clock();
cost = (double)(end - begin)/CLOCKS_PER_SEC;
printf("constant CLOCKS\_PER\_SEC is: %ld, time cost is: %lf secs", CLOCKS_PER_SEC, cost);
}
constant CLOCKS_PER_SEC is: 1000, time cost is: 0.055000 secs
55 ms/ 100000000 = 55000 us/100000000 = 0.00055 us = 0.55 ns
整型乘 和 整型加和减也差不多。
整型除 相比上面会更耗时,但量级差不多。
浮点型加和减
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
clock\_t begin, end;
double cost;
//开始记录
begin = clock();
/\*待测试程序段\*/
double a = 1.0;
for (int i = 0; i < 100000000; i++) {
a = a + 1;//a = a-1;
}
//结束记录
end = clock();
cost = (double)(end - begin)/CLOCKS_PER_SEC;
printf("constant CLOCKS\_PER\_SEC is: %ld, time cost is: %lf secs", CLOCKS_PER_SEC, cost);
}
constant CLOCKS_PER_SEC is: 1000, time cost is: 0.273000 secs
可以看出浮点型的加和减耗时大概是整型加减的5倍
浮点乘除:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
clock\_t begin, end;
double cost;
//开始记录
begin = clock();
/\*待测试程序段\*/
double a = 1.0;
for (int i = 0; i < 100000000; i++) {
a = a / i;
}
//结束记录
end = clock();
cost = (double)(end - begin)/CLOCKS_PER_SEC;
printf("constant CLOCKS\_PER\_SEC is: %ld, time cost is: %lf secs", CLOCKS_PER_SEC, cost);
}
constant CLOCKS_PER_SEC is: 1000, time cost is: 0.509000 secs
浮点型的乘和除耗时大概是浮点型的加和减耗时的2倍。
但总体来看进行算术运算的耗时还是比较小的。
测试打印printf
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
clock\_t begin, end;
double cost;
//开始记录
begin = clock();
/\*待测试程序段\*/
for (int i = 0; i <