VC获取系统时间、程序运行时间

1. time_t time(time_t* timer);
  • 功能: 该函数根据系统时钟, 返回自UTC时间1970.1.1.00:00:00以来的秒数, 或者-1表示错误;  
  • 参数: timer指向存储时间的指针. 如果为空, 不存储返回值. 如, 可这么使用: time_t ltime = time(NULL);
  • 说明: VC2005中, time是对_time64的封装, time_t默认等于__time64_t. 如果需要编译器把time_t解释为老的32位time_t, 则需要定义_USE_32BIT_TIME_T(64位平台可用), 但是不推荐这么做, 因为2038.1.18以后程序可能崩溃;
  • 头文件: <time.h>.

// crt_times.c
// compile with: /W3
// This program demonstrates these time and date functions:
//      time         _ftime    ctime_s     asctime_s
//      _localtime64_s    _gmtime64_s    mktime    _tzset
//      _strtime_s     _strdate_s  strftime
//
// Also the global variable:
//      _tzname
//

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include <string.h>

int main()
{
    char tmpbuf[128], timebuf[26], ampm[] = "AM";
    time_t ltime;
    struct _timeb tstruct;
    struct tm today, gmt, xmas = { 0, 0, 12, 25, 11, 93 };
    errno_t err;

    // Set time zone from TZ environment variable. If TZ is not set,
    // the operating system is queried to obtain the default value
    // for the variable.
    //
    _tzset();

    // Display operating system-style date and time.
    _strtime_s( tmpbuf, 128 );
    printf( "OS time:/t/t/t/t%s/n", tmpbuf );
    _strdate_s( tmpbuf, 128 );
    printf( "OS date:/t/t/t/t%s/n", tmpbuf );

    // Get UNIX-style time and display as number and string.
    time( &ltime );
    printf( "Time in seconds since UTC 1/1/70:/t%ld/n", ltime );
    err = ctime_s(timebuf, 26, &ltime);
    if (err)
    {
        printf("ctime_s failed due to an invalid argument.");
        exit(1);
    }
    printf( "UNIX time and date:/t/t/t%s", timebuf );

    // Display UTC.
    err = _gmtime64_s( &gmt, &ltime );
    if (err)
    {
        printf("_gmtime64_s failed due to an invalid argument.");
    }
    err = asctime_s(timebuf, 26, &gmt);
    if (err)
    {
        printf("asctime_s failed due to an invalid argument.");
        exit(1);
    }
    printf( "Coordinated universal time:/t/t%s", timebuf );

    // Convert to time structure and adjust for PM if necessary.
    err = _localtime64_s( &today, &ltime );
    if (err)
    {
        printf("_localtime64_s failed due to an invalid argument.");
        exit(1);
    }
    if( today.tm_hour >= 12 )
    {
        strcpy_s( ampm, sizeof(ampm), "PM" );
        today.tm_hour -= 12;
    }
    if( today.tm_hour == 0 )  // Adjust if midnight hour.
        today.tm_hour = 12;

    // Convert today into an ASCII string
    err = asctime_s(timebuf, 26, &today);
    if (err)
    {
        printf("asctime_s failed due to an invalid argument.");
        exit(1);
    }

    // Note how pointer addition is used to skip the first 11
    // characters and printf is used to trim off terminating
    // characters.
    //
    printf( "12-hour time:/t/t/t/t%.8s %s/n",
        timebuf + 11, ampm );

    // Print additional time information.
    _ftime( &tstruct ); // C4996
    // Note: _ftime is deprecated; consider using _ftime_s instead
    printf( "Plus milliseconds:/t/t/t%u/n", tstruct.millitm );
    printf( "Zone difference in hours from UTC:/t%u/n",
        tstruct.timezone/60 );
    printf( "Time zone name:/t/t/t/t%s/n", _tzname[0] ); //C4996
    // Note: _tzname is deprecated; consider using _get_tzname
    printf( "Daylight savings:/t/t/t%s/n",
        tstruct.dstflag ? "YES" : "NO" );

    // Make time for noon on Christmas, 1993.
    if( mktime( &xmas ) != (time_t)-1 )
    {
        err = asctime_s(timebuf, 26, &xmas);
        if (err)
        {
            printf("asctime_s failed due to an invalid argument.");
            exit(1);
        }
        printf( "Christmas/t/t/t/t%s/n", timebuf );
    }

    // Use time structure to build a customized time string.
    err = _localtime64_s( &today, &ltime );
    if (err)
    {
        printf(" _localtime64_s failed due to invalid arguments.");
        exit(1);
    }

    // Use strftime to build a customized time string.
    strftime( tmpbuf, 128,
        "Today is %A, day %d of %B in the year %Y./n", &today );
    printf( tmpbuf );
}

输出:

OS time:                                08:56:31
OS date:                                12/15/09
Time in seconds since UTC 1/1/70:       1260838591
UNIX time and date:                     Tue Dec 15 08:56:31 2009
Coordinated universal time:             Tue Dec 15 00:56:31 2009
12-hour time:                           08:56:31 AM
Plus milliseconds:                      46
Zone difference in hours from UTC:      4294967288
Time zone name:                         中国标准时间
Daylight savings:                       NO
Christmas                               Sat Dec 25 12:00:00 1993

Today is Tuesday, day 15 of December in the year 2009.

 2. 使用CTime类
CString str;
//获取系统时间
CTime tm;
tm=CTime::GetCurrentTime();
str=tm.Format("现在时间是%Y年%m月%d日 %X");
MessageBox(str,NULL,MB_OK);
3. 使用GetLocalTime/GetSystemTime
SYSTEMTIME st;
CString strDate,strTime;
GetLocalTime(&st);
strDate.Format("%4d-%2d-%2d",st.wYear,st.wMonth,st.wDay);
strTime.Format("%2d:%2d:%2d",st.wHour,st.wMinute,st.wSecond);
4. 使用GetTickCount
//获取程序运行时间
long t1=GetTickCount();//程序段开始前取得系统运行时间(ms)
Sleep(500);
long t2=GetTickCount();();//程序段结束后取得系统运行时间(ms)
str.Format("time:%dms",t2-t1);//前后之差即 程序运行时间
AfxMessageBox(str);

//获取系统运行时间
longt=GetTickCount();
CString str,str1;
str1.Format("系统已运行 %d时",t/3600000);
str=str1;
t%=3600000;
str1.Format("%d分",t/60000);
str+=str1;
t%=60000;
str1.Format("%d秒",t/1000);
str+=str1;
AfxMessageBox(str);
5. 获取程序运行时间clock
  • clock_t clock( void );
  • 说明: 该函数返回进程运行的时间片(time tick)数(等于"秒数 * CLOCKS_PER_SEC"), 一个time tick约等于1/CLOCKS_PER_SEC秒. 所以, 如果要得到进程运行的秒数, 需要用"返回值 / CLOCKS_PER_SEC"来转换. 如果不能得到运行时间, 返回-1, 转换为clock_t.
  • 头文件: <time.h>
// crt_clock.c
// This example prompts for how long
// the program is to run and then continuously
// displays the elapsed time for that period.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sleep( clock_t wait );
int main( void )
{
   long    i = 6000000L;
   clock_t start, finish;
   double  duration;
   // Delay for a specified time.
   printf( "Delay for three seconds/n" );
   sleep( (clock_t)3 * CLOCKS_PER_SEC );
   printf( "Done!/n" );
   // Measure the duration of an event.
   printf( "Time to do %ld empty loops is ", i );
   start = clock();
   while( i-- )
      ;
   finish = clock();
   duration = (double)(finish - start) / CLOCKS_PER_SEC;
   printf( "%2.1f seconds/n", duration );
}
 
// Pauses for a specified number of milliseconds.
void sleep( clock_t wait )
{
   clock_t goal;
   goal = wait + clock();
   while( goal > clock() )
      ;
}
 
输出:
 
Delay for three seconds
Done!
Time to do 6000000 empty loops is 0.1 seconds
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值