红糖糍粑
我总是使用clock_gettime()函数,从CLOCK_MONOTONIC时钟返回时间。返回的时间是从过去的一些未指定的点开始的时间量,以秒和纳秒为单位,例如系统启动时期。#include <stdio.h>#include <stdint.h>#include <time.h>int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p){
return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);}int main(int argc, char **argv){
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
// Some code I am interested in measuring
clock_gettime(CLOCK_MONOTONIC, &end);
uint64_t timeElapsed = timespecDiff(&end, &start);}