2009-11-14 57 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