c 获得毫秒
Linux系统
使用gettimeofday接口:gettimeofday能得到微秒数,比毫秒还要更精确。 #include <stdio.h> #include <sys/time.h> int main() { struct timeval start, end; gettimeofday( &start, NULL ); sleep(3); gettimeofday( &end, NULL ); int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; printf("time: %d us\n", timeuse); return 0; }
使用ftime接口: #include <stdio.h> #include <sys/timeb.h> long long getSystemTime() { struct timeb t; ftime(&t); return 1000 * t.time + t.millitm; } int main() { long long start=getSystemTime(); sleep(3); long long end=getSystemTime();
printf("time: %lld ms\n", end-start);
return 0;
}
Windows系统
使用GetTickCount接口: #include <windows.h> #include <stdio.h> int main() { DWORD start, stop; start = GetTickCount(); Sleep(3000); stop = GetTickCount(); printf("time: %lld ms\n", stop - start); return 0; } Windows系统下有些编译器使用printf输出64位整数参数要使用%I64d,比如VC。
使用QueryPerformanceX接口: #include <windows.h> #include <stdio.h> int main(){ LARGE_INTEGER li; LONGLONG start, end, freq; QueryPerformanceFrequency(&li); freq = li.QuadPart; QueryPerformanceCounter(&li); start = li.QuadPart; Sleep(3000); QueryPerformanceCounter(&li); end = li.QuadPart; int useTime =(int)((end - start) * 1000 / freq); printf("time: %d ms\n", useTime); return 0; }
使用GetSystemTime接口:
#include <windows.h>
#include <stdio.h>
int main(){
SYSTEMTIME currentTime;
GetSystemTime(¤tTime);
printf("time: %u/%u/%u %u:%u:%u:%u %d\n",
currentTime.wYear,currentTime.wMonth,currentTime.wDay,
currentTime.wHour,currentTime.wMinute,currentTime.wSecond,
currentTime.wMilliseconds,currentTime.wDayOfWeek);
return 0;
}