1. 程式人生 > >C++ 獲取時間間隔精確到ms

C++ 獲取時間間隔精確到ms

	struct timeb tb;
	struct tm now = {0};
	char sec1[16];
	char mss1[4];
	char sec2[16];
	char mss2[4];
	int min1, s1, ms1, min2, s2, ms2, timespan;

	ftime(&tb);
	localtime_s(&now, &tb.time);
	sprintf_s(sec1, "%02d-%02d", now.tm_min, now.tm_sec);
	sprintf_s(mss1, "%03d", tb.millitm);
	printf("%s.%s \n", sec1, mss1);
	min1 = now.tm_min;
	s1 = now.tm_sec;
	ms1 = tb.millitm;



    //your code


	ftime(&tb);
	localtime_s(&now, &tb.time);
	sprintf_s(sec2, "%02d-%02d", now.tm_min, now.tm_sec);
	sprintf_s(mss2, "%03d", tb.millitm);
	printf("%s.%s \n", sec2, mss2);
	min2 = now.tm_min;
	s2 = now.tm_sec;
	ms2 = tb.millitm;
	//int timespan = (min2 * 60 + s2 - min1 * 60 - s1) * 1000 + ms2 - ms1;
	timespan = ((min2 - min1) * 60 + s2 - s1) * 1000 + ms2 - ms1;
	printf("map間隔%d ms\n", timespan);

 

需新增#include <time.h>      //新增標頭檔案
#include <sys/timeb.h> 兩個頭函式