2009-11-14 54 views
9

我正在編寫一個將在Solaris機器上使用的程序。我需要一種記錄程序啓動後已經過去多少秒的方法。我在這裏說話很簡單。例如,我會有一個int秒= 0;但是我怎麼會每秒更新秒變量?C++跟蹤程序啓動後已經過去了多少秒

看來,我看過的各種時間函數只能在Windows機器上運行,所以我只是不確定。

任何建議,將不勝感激。

謝謝你的時間。

+0

你每秒需要一個事件嗎?更新什麼?或者只是程序運行的總時間? – Dani 2009-11-14 19:31:17

回答

0

您只需要存儲應用程序啓動時的日期/時間。無論何時您需要顯示您的程序運行多長時間,都可以獲取當前日期/時間並減去應用程序啓動時的時間。

20

一個非常簡單的方法:

#include <time.h> 
time_t start = time(0); 

double seconds_since_start = difftime(time(0), start); 

本的主要缺點是,你必須輪詢更新。您需要平臺支持或其他lib/framework才能在事件的基礎上執行此操作。

+3

'time()'返回掛鐘時間,'clock()'返回處理器時間。 – 2009-11-14 19:31:25

+0

+1男人,我很困惑的日期/時間的東西總是:) – AraK 2009-11-14 19:36:16

+0

'時鐘()'也可能是有用的,因爲OP只對經過的時間感興趣,牆壁時間可能不是必要的。另外,對於長時間運行的程序,'time()'可能會受到像NTP漂移,DST,用戶更改等等的影響......這可能會導致結果。 – jheddings 2009-11-14 19:36:46

4

你正在向後靠近。您不必擔心變量會每秒更新一次,只需在程序開始時用當前時間初始化一個變量,然後每當您需要知道已經過了多少秒時,就會從該初始時間減去當前時間。這種方式的開銷少得多,並且不需要護理一些與時間有關的變量更新。

+1

「護理」變量 - 現在這是一個概念!出於性能考慮,我經常忽略它。總的AHA時刻在這裏...... – FredTheWebGuy 2013-06-07 19:38:14

1
#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也只是刪除取勝裁判

10

使用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應該足夠了。

+1

std :: chrono在C++ 11中是新的,所以你的編譯器可能不支持它。 – frnknstn 2014-04-03 10:15:20

+2

我對C++ 11方法的答案+1,但不幸的是,它不能在啓用了C++ 11的GCC 4.8.4上編譯。雖然在輸出中使用了'duration_cast':'std :: chrono :: duration_cast >(current_time - start_time).count()'。 – Scylardor 2015-11-20 20:30:25