我正在编写一个将在Solaris机器上使用的程序。我需要一种记录程序启动后已经过去多少秒的方法。我在这里说话很简单。例如,我会有一个int秒= 0;但是我怎么会每秒更新秒变量?C++跟踪程序启动后已经过去了多少秒
看来,我看过的各种时间函数只能在Windows机器上运行,所以我只是不确定。
任何建议,将不胜感激。
谢谢你的时间。
我正在编写一个将在Solaris机器上使用的程序。我需要一种记录程序启动后已经过去多少秒的方法。我在这里说话很简单。例如,我会有一个int秒= 0;但是我怎么会每秒更新秒变量?C++跟踪程序启动后已经过去了多少秒
看来,我看过的各种时间函数只能在Windows机器上运行,所以我只是不确定。
任何建议,将不胜感激。
谢谢你的时间。
您只需要存储应用程序启动时的日期/时间。无论何时您需要显示您的程序运行多长时间,都可以获取当前日期/时间并减去应用程序启动时的时间。
一个非常简单的方法:
#include <time.h>
time_t start = time(0);
double seconds_since_start = difftime(time(0), start);
本的主要缺点是,你必须轮询更新。您需要平台支持或其他lib/framework才能在事件的基础上执行此操作。
你正在向后靠近。您不必担心变量会每秒更新一次,只需在程序开始时用当前时间初始化一个变量,然后每当您需要知道已经过了多少秒时,就会从该初始时间减去当前时间。这种方式的开销少得多,并且不需要护理一些与时间有关的变量更新。
“护理”变量 - 现在这是一个概念!出于性能考虑,我经常忽略它。总的AHA时刻在这里...... – FredTheWebGuy 2013-06-07 19:38:14
#include <stdio.h>
#include <time.h>
#include <windows.h>
using namespace std;
void wait (int seconds);
int main()
{
time_t start, end;
double diff;
time (&start); //useful call
for (int i=0;i<10;i++) //this loop is useless, just to pass some time.
{
printf ("%s\n", ctime(&start));
wait(1);
}
time (&end);//useful call
diff = difftime(end,start);//this will give you time spent between those two calls.
printf("difference in seconds=%f",diff); //convert secs as u like
system("pause");
return 0;
}
void wait (int seconds)
{
clock_t endwait;
endwait = clock() + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
这应该solaris上精细/ UNIX也只是删除取胜裁判
使用std::chrono。
#include <chrono>
#include <iostream>
int main(int argc, char *argv[])
{
auto start_time = std::chrono::high_resolution_clock::now();
auto current_time = std::chrono::high_resolution_clock::now();
std::cout << "Program has been running for " << std::chrono::duration_cast<std::chrono::seconds>(current_time - start_time).count() << " seconds" << std::endl;
return 0;
}
如果您只需要秒的分辨率,那么std::steady_clock应该足够了。
你每秒需要一个事件吗?更新什么?或者只是程序运行的总时间? – Dani 2009-11-14 19:31:17