C语言计时函数

本文详细介绍了C语言中用于计时的各种函数,如time()、clock()、timespec_get()等,以及Windows平台特有的timeGetTime()、GetTickCount()、QueryPerformanceCounter()等。讨论了它们的时间精度、适用场景及潜在问题,帮助读者理解如何在C语言中实现精确计时。
摘要由CSDN通过智能技术生成

time()函数与time_t类型

头文件:time.h

函数签名time_t time( time_t *arg )

说明:返回当前计算机纪元时间,并将其存储在arg指向的time_t类型中。所以可以time_t result = time(NULL),也可以time(&result)

计算机纪元时间:C语言和Unix创造并诞生于1970年,所以计算机以1970年1月1日作为纪元开始时间。

C语言标准并没有指定time_t类型的编码方式,但大多数遵循POSIX标准系统的time_t一般是32位有符号整数实现,以秒为最小单位,从1970年1月1日开始计数,所以能表示到2038年。

VS2017中有如下定义:

#ifndef _CRT_NO_TIME_T
    #ifdef _USE_32BIT_TIME_T
        typedef __time32_t time_t;
    #else
        typedef __time64_t time_t;
    #endif
#endif

...
#ifdef _USE_32BIT_TIME_T
    ...
        static __inline time_t __CRTDECL time(
        _Out_opt_ time_t* const _Time
        )
    {
        return _time32(_Time);
    }
    ...
#else
    ...
    static __inline time_t __CRTDECL time(
        _Out_opt_ time_t* const _Time
        )
    {
        return _time64(_Time);
    }
    ...
#endif

因为time_t类型编码不能确定,所以尽量不要用t1-t2方式计算两个time_t之间的时间间隔,而应该用double difftime( time_t time_end, time_t time_beg );函数计算时间间隔。

扩展time_t表示计算机纪元时间,struct tm表示标准日历时间。

struct tm定义如下:

struct tm
{
    int tm_sec;   // seconds after the minute - [0, 60] including leap second
    int tm_min;   // minutes after the hour - [0, 59]
    int tm_hour;  // hours since midnight - [0, 23]
    int tm_mday;  // day of the month - [1, 31]
    int tm_mon;   // months since January - [0, 11]
    int tm_year;  // years since 1900
    int tm_wday;  // days since Sunday - [0, 6]
    int tm_yday;  // days since January 1 - [0, 365]
    int tm_isdst; // daylight savings time flag
};

time_t可以和struct tm格式的时间进行互相转换:

  • struct tm *gmtime( const time_t *time ):从time_t转成struct tm,但该函数C11标准中才定义的。
  • time_t mktime( struct tm *time ):从struct tm转成time_t

示例

    time_t start, end;
    start = time(NULL);
    _sleep(1000);
    end = time(NU
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值