#include <iostream>
#include <chrono>
int main() {
// 获取程序开始时间点
auto start_time_point = std::chrono::high_resolution_clock::now();
// 这里放置你的程序代码
// 获取程序结束时间点
auto end_time_point = std::chrono::high_resolution_clock::now();
// 计算时间差
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time_point - start_time_point);
// 将微秒转换为秒并输出
double elapsed_seconds = duration.count() * 1e-6;
std::cout << "Elapsed time: " << elapsed_seconds << " seconds" << std::endl;
return 0;
}
用这个可以编写一个流水灯逻辑,假设流水灯有9个,流水灯的亮灭周期为750ms,亮灯周期为450ms。
using namespace std;
#define WATER_ALL_PHASE_FRONT 750
#define WATER_OPEN_PHASE 450
#define FRAMES_PER_WATER_SECTION 45
#define WATER_LIGHT_NUM 9
int water_frame = 0;
bool water_light_is_open[WATER_LIGHT_NUM] = {0};
//接收到灯光信号,记录一下这个时间值
{
chrono::system_clock::time_point turning_light_order_start_time = 记录接受到灯光信号的时刻;
}
//下面为反复draw的图像
{
auto time_now = chrono::system_clock::now();
auto duration = chrono::system_clock::duration_cast<chrono::milliseconds>(time_now - turning_light_order_start_time);
int64_t time_duration = duration.count();
water_frames = time_duration % WATER_OPEN_PHASE;
//依次点亮每个灯
for (int i = 0; i < (water_frames / FRAMES_PER_WATER_SECTION + 1) && i < WATER_LIGHT_NUM; i++) {
water_light_is_open[i] = true;
}
//超过周期后熄灭所有流水灯,补一帧熄灭流水灯
if (water_frames >= WATER_OPEN_PHASE + 45) {
for (int i = 0; i < WATER_LIGHT_NUM; i++) {
water_light_is_open[i] = false;
}
}
//熄灭的具体操作
.....
}