我正在編寫一個將在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