在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程序的运行时长。


