使用函数 int gettimeofday(struct timeval *tv, struct timezone *tz);,struct timeval 结构体中记录了自1970年1月1日起到现在的时间即秒+微秒。
能获得微秒的时间当然更可以获得毫秒的时间了,只要从微秒换算到毫秒就好了。#include <sys/time.h> #include <stdio.h> #include <unistd.h> int main() { struct timeval begin; struct timeval end; gettimeofday(&begin, NULL); usleep(100); gettimeofday(&end, NULL); printf("sleep %ld us\n", (long)(end.tv_sec - begin.tv_sec) * 1000000 + end.tv_usec - begin.tv_usec); return 0; }