Linux下时间转换与计算

2020-06-22  本文已影响0人  小五愣
  1. 头文件
#include <unistd.h>     // sleep 函数头文件
#include <time.h>       // 结构体time_t和函数time
#include <sys/time.h>   // 结构体timeval和函数select,gettimeofday的头文件
  1. 时间戳转成字符串
int timeToStr(time_t nowT ){
  //time_t nowT ;      // time_t就是long int 类型
  nowT = time(0);    // 取得当前时间 ,秒级
  printf("now time=%ld\n", nowT);         //now time=1561970448
  char strT[32];
  /* 使用 strftime 将时间格式化成字符串("YYYY-MM-DD hh:mm:ss"格式)*/
  strftime(strT, sizeof(strT), "%Y-%m-%d %H:%M:%S", localtime(&nowT));
  printf("%s\n",strT);
}
  1. 字符串转成时间戳
long strToTime(char *str_time){
    struct tm stm;
    strptime(str_time, "%Y-%m-%d %H:%M:%S",&stm);
    long t = mktime(&stm);
    return t;
}
  1. 自定义ms延时
void msleep(int ms){
    struct timeval delay;
    delay.tv_sec = 0;
    delay.tv_usec = ms * 1000; // 20 ms
    select(0, NULL, NULL, NULL, &delay);
}
  1. 利用omp计算时间
#include <omp.h>
double t1, t2;
t1 = omp_get_wtime();
//TUDO
t2 = omp_get_wtime();
printf("###stage1 cost time: %.6f ms###\n", (t2 -t1) * 1000);
上一篇 下一篇

猜你喜欢

热点阅读