首页 > 技术文章 > (二)linux的计时函数

walkinginthesun 2018-06-04 01:05 原文

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;
}

推荐阅读