在Linux中,可以使用clock_gettime
函数来获取程序的运行时长。clock_gettime
函数可以返回一个结构体timespec
,其中包含程序开始运行到当前时间的时长。具体操作步骤如下:
包含需要的头文件:#include <time.h>
在程序开始处调用clock_gettime
函数,获取程序开始运行的时间戳:
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
clock_gettime
函数,获取当前时间戳:clock_gettime(CLOCK_MONOTONIC, &end);
long seconds = end.tv_sec - start.tv_sec;
long nanoseconds = end.tv_nsec - start.tv_nsec;
if (nanoseconds < 0) {
seconds--;
nanoseconds += 1000000000;
}
printf("程序运行时长:%ld 秒 %ld 纳秒\n", seconds, nanoseconds);
通过以上步骤,就可以通过clock_gettime
函数计算Linux程序的运行时长。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:如何通过gettickcount获取Linux系统的运行时间