C++:记录经过的时间

发布于 2024-11-04 01:57:22 字数 248 浏览 5 评论 0原文

我正在寻找一种方法,能够在任何给定时间知道自我的程序启动以来已经过去了多少时间。一种计时器,当主代码执行其他操作时,它会继续运行,并且可以随时调用。

上下文是 Windows 上的 OpenGL 应用程序,除了知道按下了哪些键盘键(使用 glutKeyboardFunc)外,我还想知道每个键何时按下。所有这些信息都写入一个 XML 文件,稍后将用于重放用户所做的一切。 (有点像赛车游戏中的重播功能,但更简单)。

I'm looking for a way to be able to know how much time it's been since my program was started, at any given time. A sort of timer that would keep running while the main code is doing everything else, and that can be called at any time.

The context is an OpenGL application on Windows, and as well as knowing which keyboard keys are being pressed (using glutKeyboardFunc), I'd like to know when exactly each key is pressed. All of this info is written into an XML file that will later be used to replay everything the user did. (sort of like the replay functionality in a car racing game, but more simple).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小矜持 2024-11-11 01:57:23

C++ 11:

#include <iostream>
#include <chrono>

auto start = std::chrono::system_clock::now();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";

代码取自en.cppreference.com< /a> 并简化

旧答案:
windows.h 中的 GetTickCount() 返回经过的时间间隔(毫秒)。
当您的应用程序启动时,调用此函数并存储其值,然后每当您需要知道自程序启动以来经过的时间时,请再次调用此方法并从起始值中减去其值。

int start = GetTickCount(); // At Program Start

int elapsed = GetTickCount() - start; // This is elapsed time since start of your program

C++ 11:

#include <iostream>
#include <chrono>

auto start = std::chrono::system_clock::now();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";

Code taken from en.cppreference.com and simplified.

Old answer:
GetTickCount() in windows.h returns ticks(miliseconds) elapsed.
When your app starts, call this function and store its value, then whenever you need to know elapsed time since your program start, call this method again and subtract its value from start value.

int start = GetTickCount(); // At Program Start

int elapsed = GetTickCount() - start; // This is elapsed time since start of your program
め七分饶幸 2024-11-11 01:57:23

为此,您不需要计时器,只需在应用启动时使用 time(0) 保存时间戳。每次你想要测量时间时,你都会做同样的事情,你只需 init_time - current_time 就可以得到时间流逝。

You don't need a timer for this, you save the timestamp at start of the app with time(0). And the you do the same each time you want to measure the time and you can just to init_time - current_time and you'll get the time lapse.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文