• (二)linux的计时函数


    linux的计时函数,用于获取当前时间。

    1. gettimeofday()

    函数 结构体 精度
    time() time_t s
    gettimeofday() struct timeval us

    计时只使用gettimeofday()函数来获取当前时间:

    • time()函数精度太低,gettimeofday()函数以微秒为单位,可获取us/ms/s的精度,足以满足日常计时需要。

    2. redis中的计时封装函数

    /*
     * util_time.h
     *
     *  Created on: 2018-6-4
     *      Author: 
     */
    
    #ifndef UTIL_TIME_H_
    #define UTIL_TIME_H_
    
    #include <sys/time.h>
    
    /* Return the UNIX time in microseconds */
    long long ustime(void) {
        struct timeval tv;
        long long ust;
    
        gettimeofday(&tv, NULL);
        ust = ((long long)tv.tv_sec)*1000000;
        ust += tv.tv_usec;
        return ust;
    }
    
    /* Return the UNIX time in milliseconds */
    long long mstime(void) {
        return ustime()/1000;
    }
    
    // #define UTIL_TIME_TEST
    #ifdef UTIL_TIME_TEST
    #include <unistd.h>
    #include <iostream>
    
    int main()
    {
    	long long llStart = mstime();
    	sleep(2);
    	long long llEnd=mstime();
    	std::cout<<llEnd-llStart<<"ms"<<std::endl;
    
    	return 0;
    }
    #endif
    
    #endif /* UTIL_TIME_H_ */
    
    

    3. 时间戳和本地时间的转换

    #include <time.h>
    #include <iostream>
    using namespace std;
    
    int main()
    {
        // __int64 时间戳 time(nullptr)
        // 时间戳是从格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
        // 现在时间戳的长度是十位(1435113975--2015/6/24 10:46:15)
        time_t raw_time;
        raw_time = time(nullptr);
        cout << raw_time << endl;              // 1515049816
    
        // 时间戳到本地时间转换 localtime(&raw_time), asctime(time_info) convert tm structure to string.
        struct tm *time_info=nullptr;
        time_info = localtime(&raw_time);
    
    
        cout << asctime(time_info);            // Thu Jan 04 15:10 : 16 2018
        cout << time_info->tm_wday << endl;    // 4 --> 周四
    
        // 本地时间到时间戳转换 mktime(time_info)
        time_t after_time = mktime(time_info);
        cout << after_time << endl;            // 1515049816
    
        return 0;
    }
    
    
  • 相关阅读:
    Go 笔记之如何防止 goroutine 泄露
    调试 Go 的代码生成
    使用k8s容器钩子触发事件
    springboot教程
    Intellij IDEA 使用Spring-boot-devTools无效解决办法
    c# WMI获取机器硬件信息(硬盘,cpu,内存等)
    各式 Web 前端開發工具整理
    Informix 中执行多条SQL(Execute Script)
    Log4Net
    mysql 按年度、季度、月度、周、日SQL统计查询
  • 原文地址:https://www.cnblogs.com/walkinginthesun/p/9131485.html
Copyright © 2020-2023  润新知