经常遇到程序执行时间过长的时候,一般会优化程序的执行时间,优化之前需要先测量模块的执行时间,找出最占时间的函数或者模块
1、时间函数测量
头文件
#include <time.h>
函数
使用gmtime函数获取格林尼治时间,函数原型:
struct tm * gmtime(const time_t *)
测量示例
struct timespec ts1,ts2;
float time_ms = 0.0f; //用于存储识别所需的时间
int time_s;
clock_gettime(CLOCK_MONOTONIC,&ts1);
//要执行的函数
fun();
clock_gettime(CLOCK_MONOTONIC,&ts2); //CLOCK_MONOTONIC :表示系统使用的是单一时钟 记录识别结束时的当前时间
time_ms = (ts2.tv_nsec-ts1.tv_nsec)/1000000000.0; //把ns转换为s 单位s
time_s = (ts2.tv_sec -ts1.tv_sec); //得到s位时间 单位s
printf(“run time %.6f ms\n”,(time_s+time_ms)*1000); //打印使用了多长时间 单位ms
2、Io输出方波,用示波器测量
拉高电平
//要执行的函数
fun();
拉低电平
示波器测量高电平时间
3、定时器测量
启动定时器
//要执行的函数
fun();
读取定时器时间
关闭定时器
打印时间