http://www.cnblogs.com/UnGeek/archive/2013/03/08/2950863.html
//使用标准C语言的time函数,可以满足一般性需要
#include <time.h> #include <stdio.h> int main( void ) { time_t t = time( 0 ); char tmp[64]; strftime( tmp, sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z", localtime(&t) ); puts( tmp ); return 0; }
//GetLocalTime获取当前系统时间,精确到微秒级
#include <windows.h> #include <stdio.h> int main( void ) { SYSTEMTIME sys; GetLocalTime( &sys ); printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d " ,sys.wYear,sys.wMonth,sys.wDay ,sys.wHour,sys.wMinute,sys.wSecond,sys.wMilliseconds ,sys.wDayOfWeek); return 0; }
//利用win32 API QueryPerformanceFrequency与QueryPerformanceCounter,可以更精确精确的计算,例如拿来测试,网络抓包的精确分析
#include <windows.h> #include <stdio.h> #include <iostream> using namespace std; int main() { LARGE_INTEGER lv,lv_b; // 获取每秒多少CPU Performance Tick QueryPerformanceFrequency( &lv ); // 转换为每个Tick多少秒 double secondsPerTick = 1.0 / lv.QuadPart; QueryPerformanceCounter( &lv_b ); for ( size_t i = 0; i < 100; ++i ) { // 获取CPU运行到现在的Tick数 QueryPerformanceCounter( &lv ); cout.precision( 6 ); // 计算CPU运行到现在的时间 // 比GetTickCount和timeGetTime更加精确 LONGLONG duration = lv.QuadPart-lv_b.QuadPart; double timeElapsedTotal = secondsPerTick * duration; cout << fixed << showpoint << timeElapsedTotal << endl; //printf( "%lf ", timeElapsedTotal ) ; } return 0; }
//如果上面还不能满足你的需求,请看下面
http://www.boost.org/doc/libs/1_53_0/doc/html/date_time.html
可以提供纳秒级的精确计算,而且跨平台