计算程序运行时间精确到毫秒

时间:2022-10-27 17:24:16
#include<sys/timeb.h>
struct timeb t1,t2;
void main(){
ftime(&t1);
//code do something
ftime(&t2);
printf("Msecond : %ld \n",(t2.time - t1.time)*1000+t2.millitm - t1.millitm );
}
</pre><pre name="code" class="cpp">

struct timeb
{
time_t time; //秒
unsigned short millitm;//毫秒
short timezone;//时区
short dstflag;//时区标
}

timeb.h中声明了timeb结构,ftime(timeb&)获取当前时间,可以精确到毫秒级别。timeb.millitm表示毫秒
time.h中声明了tm结构体,可以记录年月日、时分秒,但不支持毫秒级的计时方式,用time(NULL)函数获取当前时间。