转载自https://www.cnblogs.com/molly/p/3764351.html
最简单的方法:
在执行文件前加上time,就会显示运行时间,如:
总结来说,user后跟的时间是真正用于执行进程所用的时间
更详细的解释:https://blog.csdn.net/q_l_s/article/details/54897684
其他方法:
linux 中的 <sys/time.h> 中 有个函数可以获取当前时间,精确到 微秒 ----> gettimeofday()
#include <sys/time.h>
// int gettimeofday(struct timeval *tv, struct timezone *tz);
/*********************************************
* struct timeval
* {
* time_t tv_sec; // seconds
* suseconds_t tv_usec; // microseconds:微秒 10^(-6)s, 这里的 tv_sec 用的是 微秒
* // millisecond :毫秒 10^(-3)s
* }
**********************************************
* struct timezone
* {
* int tz_minuteswest; // minutes west of Greenwich
* int tz_dsttime; // type of DST correction
* }
**********************************************/
使用时,定义两个 struct timeval 变量(通常 gettimeofday() 的第二个参数 设为 NULL),分别保存 代码测试 前后的时刻,最后相减,即可获取 代码运行时间 (可转换为自己需要的时间)。
#include <stdio.h>
#include <sys/time.h> // for gettimeofday()
#include <string.h> // for memset()
int main()
{
int i = 10000000;
struct timeval start, end; // define 2 struct timeval variables
//-------------------------
gettimeofday(&start, NULL); // get the beginning time
//-------------------------
// test code
while(i)
{
i--;
}
//-------------------------
gettimeofday(&end, NULL); // get the end time
//-------------------------
long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond
printf("total time is %lld us\n", total_time);
total_time /= 1000; // get the run time by millisecond
printf("total time is %lld ms\n", total_time);
}
测试结果:(CentOS 6.5, gcc 4.4.7)
total time is 49658 us
total time is 49 ms