Chinaunix首页 | 论坛 | 博客
  • 博客访问: 13841
  • 博文数量: 2
  • 博客积分: 106
  • 博客等级: 民兵
  • 技术积分: 30
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-21 13:32
文章分类

全部博文(2)

文章存档

2011年(1)

2010年(1)

最近访客

分类:

2010-12-02 22:37:43


C/C++编程中获取系统时间的方法
一、time_t结构体:
在windows平台上进行了一个扩展:__time64_t
二、各平台下的结构:
1.windows平台下的方法:SYSTEMTIME。
SYSTEMTIME结构在Winbase.h的定义如下:
typedef struct _SYSTEMTIME { // st
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME;
使用方法参看msdn。
2.linux平台下的方法:timeval。
struct timeval结构体在time.h中的定义为:
struct timeval
{
    time_t tv_sec;        /* Seconds. */
    suseconds_t tv_usec;    /* Microseconds. */
};
其中,tv_sec为Epoch到创建struct timeval时的秒数,tv_usec为微秒数(10的-6次方),即秒后面的零头。
C语言示例:
#include
#include
int main()
{
    struct timeval tv;
    gettimeofday( &tv, NULL );
    printf("time %u %u \n", tv.tv_sec, tv.tv_usec );
    return 0;
}
C++语言示例:
#include
#include
using namespace std;
extern "C"
int gettimeofday( struct timeval *tv, struct timezone *tz );
int main()
{
    timeval tv;
    gettimeofday( &tv, NULL );
    cout<    return 1;
}

C/C++编程中计算运行时间的方法
一、运用上面获取的时间相减。
二、clock_t结构。
用于计算cpu运行的时间,精确到毫秒。
(linux平台上使用的时候不包括sleep的时间,有时候计算的时间不准确)
#include
#include
using namespace std;
void test()
{
    unsigned int i = 10000000;
    while( i-- )
    {}
}
int main()
{
    clock_t t1 = clock();
    test();
    clock_t t2 = clock();
    cout<<"使用时间:"<<(double)(t2-t1)/CLOCKS_PER_SEC<<"秒"<    return 1;
}

 
阅读(1743) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:博客已升级,请注意变更地址

给主人留下些什么吧!~~