c语言linux打印运行时间(耗时) gettimeofday()、timeval、<sys/time.h>
#include <stdio.h>#include <sys/time.h>double __get_us(struct timeval t) {return (t.tv_sec * 1000000 + t.tv_usec);}int main(){struct timeval start_time, stop_time;gettimeofday(&start_t
   ·  
 #include <stdio.h>
#include <sys/time.h>
double __get_us(struct timeval t) { 
	return (t.tv_sec * 1000000 + t.tv_usec); 
}
int main(){
	struct timeval start_time, stop_time;
	gettimeofday(&start_time, NULL);
	//待运行代码
	gettimeofday(&stop_time, NULL);
	printf("Time use %f ms\n", (__get_us(stop_time) - __get_us(start_time)) / 1000);
}
示例(在ubuntu16.04上):
test.c
#include <stdio.h>	//使用printf()需要包含
#include <sys/time.h>
#include <unistd.h>	//使用sleep()函数需要包含
double __get_us(struct timeval t) {
	return (t.tv_sec * 1000000 + t.tv_usec);
}
int main() {
	struct timeval start_time, stop_time;
	gettimeofday(&start_time, NULL);
	//待运行代码
	sleep(1);
	gettimeofday(&stop_time, NULL);
	printf("Time use %f ms\n", (__get_us(stop_time) - __get_us(start_time)) / 1000);
}
编译运行结果:
[root@ubuntu /arnold_test/20211227_TEST]12# gcc test.c 
[root@ubuntu /arnold_test/20211227_TEST]13# ./a.out 
Time use 1000.994000 ms
参考文章:C语言linux gettimeofday()函数和time()函数的区别(后者只能得到秒级系统时间,前者能得到毫秒甚至微秒级系统时间)
更多推荐
 
 



所有评论(0)