1.C++输出当前的时间

我们检测视频时,一般按照当前时间存取图片,并且会设置延迟一定的时间后再存下一张图片,所以我们需要用C+实现读取当前时间和延迟时间的功能

1.读取当前时间

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <sstream>
#include <ctime>
#include <time.h>

int main()
{
	
	clock_t tstart;
  time_t t = time(nullptr); // 获取1970年到现在的毫秒数
	struct tm* now = localtime(&t); // 把毫秒转换为日期时间的结构体
 
	std::stringstream timeStr;
    
    // 以下依次把年月日的数据加入到字符串中
	timeStr << now->tm_year + 1900 << "year";
	timeStr << now->tm_mon + 1 << "month";
	timeStr << now->tm_mday << "day ";
	timeStr << now->tm_hour << ":";
	timeStr << now->tm_min << ":";
	timeStr << now->tm_sec;
 
	std::cout << timeStr.str() << std::endl;
  
	return 0;
}
 

2.延迟时间(Ubuntu环境)

#include <iostream>
#include <unistd.h>

using namespace std;

int main()
{
    double startTime,stopTime,durationTimeTime;

    startTime=time(NULL);

    sleep(0.2);

    stopTime=time(NULL);

    durationTimeTime = (double)difftime(stopTime,startTime);

    cout << "耗时(time): " << durationTimeTime << " s" << endl;


    return 0;
}

3.将以上两者结合,循环输出时_分_秒_毫秒(毫秒保留3位有效数字)

代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <sstream>
#include <ctime>
#include <time.h>

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>


int main(int argc, char *argv[])
{

    while (1)
    {time_t t = time(nullptr); // 获取1970年到现在的毫秒数
	  struct tm* now = localtime(&t); // 把毫秒转换为日期时间的结构体
 
	  std::stringstream timeStr;
    
    // 以下依次把年月日的数据加入到字符串中
  	
	  timeStr << now->tm_hour << "_";
	  timeStr << now->tm_min << "_";
	  timeStr << now->tm_sec<< "_";
     
 
    struct timeval time;
 
    /* 获取时间,理论到us */
    gettimeofday(&time, NULL);
    //printf("s: %ld, ms: %ld\n", time.tv_sec, (time.tv_sec*1000 + time.tv_usec/1000));
    timeStr <<time.tv_usec/1000;
    std::cout << timeStr.str() << std::endl;
    
 
    usleep(300000);}  //延时   usleep:微秒   sleep:秒
    
    return 0;
    
}

,输出结果如下:

这种时间可以作为当天的pcd或者摄像头图片的名称。

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值