最近在跑一些程序,需要计算程序运行的时间,然后搜索了一下相关的材料,发现下面的一个比较好的方法,可以实现毫秒级的计时:
#include <sys/timeb.h>
time_t ltime1, ltime2, tmp_time;
struct TIMEB tstruct1, tstruct2;
ftime (&tstruct1); // start time ms
time (<ime1); // start time s
// work
time (<ime2); // end time sec
ftime (&tstruct2); // end time ms
tmp_time = (ltime2 * 1000 + tstruct2.millitm) - (ltime1 * 1000 + tstruct1.millitm);
#if defined(WIN32)
# define TIMEB _timeb
# define ftime _ftime
#else
#define TIMEB timeb
#endif
# define TIMEB _timeb
# define ftime _ftime
#else
#define TIMEB timeb
#endif
time_t ltime1, ltime2, tmp_time;
struct TIMEB tstruct1, tstruct2;
ftime (&tstruct1); // start time ms
time (<ime1); // start time s
// work
time (<ime2); // end time sec
ftime (&tstruct2); // end time ms
tmp_time = (ltime2 * 1000 + tstruct2.millitm) - (ltime1 * 1000 + tstruct1.millitm);