C C++语言性能分析方法及性能分析工具的使用

VxWorks实时性能探究

测试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 <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值