加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C++ 时间操作(获取毫秒级)

(2013-04-09 16:15:20)
标签:

it

分类: 03_边边角角积累

http://www.cnblogs.com/UnGeek/archive/2013/03/08/2950863.html

//使用标准C语言的time函数,可以满足一般性需要

#include

#include

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

#include

int main( void )

{

SYSTEMTIME sys;

GetLocalTime( &sys );

printf( "M/d/d d:d:d.d 星期\n"

,sys.wYear,sys.wMonth,sys.wDay

,sys.wHour,sys.wMinute,sys.wSecond,sys.wMilliseconds

,sys.wDayOfWeek);

 

return 0;
}

 

//利用win32 API  QueryPerformanceFrequency与QueryPerformanceCounter,可以更精确精确的计算,例如拿来测试,网络抓包的精确分析

#include

#include
#include
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 \n", timeElapsedTotal ) ;
    }
    return 0;
}
//如果上面还不能满足你的需求,请看下面

http://www.boost.org/doc/libs/1_53_0/doc/html/date_time.html

可以提供纳秒级的精确计算,而且跨平台



 

CString GetTimeStr() 

SYSTEMTIME time;

GetLocalTime(&time);


CString year;

CString month;

CString day;

year.Format(_T("%d"), time.wYear);

month.Format(_T("%d"), time.wMonth);

day.Format(_T("%d"), time.wDay);

month = time.wMonth < 10 ? (_T("0") + month):month;

day = time.wDay < 10 ? (_T("0") + day):day;

wstring strTime = year + _T("/") + month + _T("/") + day + _T(" ");


WCHAR* pTime = new WCHAR[30];

wstring strFormat = _T("HH:mm:ss");

GetTimeFormat(LOCALE_INVARIANT , LOCALE_USE_CP_ACP, &time, strFormat.c_str(), pTime, 30);

strTime += pTime;


CString milliseconds;

milliseconds.Format(_T("%d"), time.wMilliseconds);

strTime += _T(".") + milliseconds;

return strTime.c_str();

}

返回的日期时间的格式 如:2012/04/10 14:32:25.456

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有