• ftime() 系统时间


    ftime() 函数,这个函数是取系统的时间,精确到毫秒级别,它在windows 和linux 下都可用。所以我暂时是比较喜欢它的。

    这个函数返回一个结构体,结构体中两个成员,其中time 成员,与函数 time(NULL) 返回的是等同的,用它可以配合localtime mktime ctime 等时间函数作相应的时间操作。

     1 #include <stdio.h>
     2 #include <sys/timeb.h>
     3 
     4 void main_tick(time_t cur_sec)
     5 {
     6 
     7 }
     8 
     9 int main()
    10 {
    11     int msec_per_tick = 20;    // 每一个TICK 的毫秒值
    12 
    13     struct timeb s_tp_cur = {0, 0};
    14     struct timeb s_tp_fin = {0, 0}; 
    15     int next_millitm = 0;    // 当前时间经过一个tick 之后的毫秒值,在未进位到秒之前
    16     int surplus_msec = 0;    // 剩余tick 毫秒值: > 0 代表需要休眠
    17     ftime(&s_tp_cur);
    18     s_tp_fin = s_tp_cur;
    19 
    20     int count = 50;
    21     while (count-- >= 0)
    22     {
    23         //< 主tick 开始
    24         main_tick(s_tp_cur.time);
    25         //< 主tick 结束
    26 
    27         ftime(&s_tp_cur);
    28 
    29         surplus_msec = (int)(s_tp_fin.time - s_tp_cur.time) * 1000
    30             + (s_tp_fin.millitm - s_tp_cur.millitm);
    31 #if defined OS_WINDOWS
    32         printf("beg: %lld.%d, end: %lld.%d, surplus_msec = %d
    ", 
    33             s_tp_cur.time, s_tp_cur.millitm, 
    34             s_tp_fin.time, s_tp_fin.millitm, 
    35             surplus_msec);
    36 #elif defined OS_LINUX
    37         printf("beg: %ld.%d, end: %ld.%d, surplus_msec = %d
    ", 
    38             s_tp_cur.time, s_tp_cur.millitm, 
    39             s_tp_fin.time, s_tp_fin.millitm, 
    40             surplus_msec);
    41 #endif
    42 
    43         if (surplus_msec > 0)
    44         {
    45             printf("Sleep(%d)
    ", surplus_msec);
    46             next_millitm = s_tp_cur.millitm + msec_per_tick + surplus_msec;
    47 #if defined OS_WINDOWS
    48             Sleep(surplus_msec);
    49 #elif defined OS_LINUX
    50             usleep(surplus_msec * 1000);
    51 #endif
    52         }
    53         else
    54         {
    55             next_millitm = s_tp_cur.millitm + msec_per_tick;
    56         }
    57 
    58         // 计算tick 时间到的end 值
    59         s_tp_fin.time    = s_tp_cur.time + next_millitm / 1000;
    60         s_tp_fin.millitm = next_millitm % 1000;
    61     };
    62 
    63     return 0;
    64 }
  • 相关阅读:
    使用NoSQL Manager for MongoDBclient连接mongodb
    Shell编程(二)条件控制,流程控制及循环控制
    Shell编程(一)参数引用,特殊字符及常用的操作符
    日常使用的linux总结记录--不断更新中
    oracle数据库中的连表查询
    前端css样式2
    前端css样式
    前端基础知识
    mysql执行计划, 事务处理
    sql 索引优化
  • 原文地址:https://www.cnblogs.com/suyunhong/p/4489066.html
Copyright © 2020-2023  润新知