如何在 C + + 中计算时差

用 C + + 计算时差的最佳方法是什么?我在计算程序的执行速度,所以我对毫秒感兴趣。更好的是,几秒,几毫秒。.

接受的答案是可行的,但是需要包含 ctime 或 time.h,如注释中所示。

280851 次浏览

参见 std::clock()函数。

const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) /  CLOCKS_PER_SEC;

如果您想计算 self (而不是用户)的执行时间,最好是以时钟滴答(而不是秒)的形式进行。

编辑:
负责的头文件 -<ctime><time.h>

只是一个附带说明: 如果您在 Windows 上运行,并且确实需要精度,那么可以使用 QueryPerformanceCounter 查询性能计数器。它给你的时间(可能) 纳米机器人秒。

以毫秒为单位计算系统时间,在开始和结束时再次计算,然后减去。

要在 POSIX 中得到自1970年以来的毫秒数,您可以写:

struct timeval tv;


gettimeofday(&tv, NULL);
return ((((unsigned long long)tv.tv_sec) * 1000) +
(((unsigned long long)tv.tv_usec) / 1000));

要得到 Windows 上自1601以来的毫秒数,你可以这样写:

SYSTEMTIME systime;
FILETIME filetime;


GetSystemTime(&systime);
if (!SystemTimeToFileTime(&systime, &filetime))
return 0;


unsigned long long ns_since_1601;
ULARGE_INTEGER* ptr = (ULARGE_INTEGER*)&ns_since_1601;


// copy the result into the ULARGE_INTEGER; this is actually
// copying the result into the ns_since_1601 unsigned long long.
ptr->u.LowPart = filetime.dwLowDateTime;
ptr->u.HighPart = filetime.dwHighDateTime;


// Compute the number of milliseconds since 1601; we have to
// divide by 10,000, since the current value is the number of 100ns
// intervals since 1601, not ms.
return (ns_since_1601 / 10000);

如果您想规范化 Windows 的答案,以便它也返回自1970年以来的毫秒数,那么您必须将您的答案调整11644473600000毫秒。但是如果你关心的只是时间流逝,那就没有必要了。

我会认真考虑 Boost 的使用,特别是升压: : posx _ time: : ptime 和升压: : posx _ time: : time _ duration (at http://www.boost.org/doc/libs/1_38_0/doc/html/date_time/posix_time.html)。

它是跨平台的,易于使用,而且根据我的经验,它提供了操作系统所能提供的最高级别的时间分辨率。可能也非常重要; 它提供了一些非常好的 IO 操作符。

要用它来计算程序执行的差异(以微秒为单位; 可能有些过度) ,它看起来像这样(浏览器已编写,未测试) :

ptime time_start(microsec_clock::local_time());
//... execution goes here ...
ptime time_end(microsec_clock::local_time());
time_duration duration(time_end - time_start);
cout << duration << '\n';

如果你在 Unix 上,你可以使用 time得到执行时间:

$ g++ myprog.cpp -o myprog
$ time ./myprog

在 Windows 中: 使用 去拿票

//GetTickCount defintition
#include <windows.h>
int main()
{


DWORD dw1 = GetTickCount();


//Do something


DWORD dw2 = GetTickCount();


cout<<"Time difference is "<<(dw2-dw1)<<" milliSeconds"<<endl;


}

你也可以使用 时钟 _ gettime。这个方法可以用来测量:

  1. 全系统实时时钟
  2. 全系统单调时钟
  3. 每进程 CPU 时间
  4. 每进程线程 CPU 时间

守则如下:

#include < time.h >
#include <iostream>
int main(){
timespec ts_beg, ts_end;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_beg);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_end);
std::cout << (ts_end.tv_sec - ts_beg.tv_sec) + (ts_end.tv_nsec - ts_beg.tv_nsec) / 1e9 << " sec";
}

`

升级1.46.0及以上版本包括 Chrono库:

Thread _ lock 类提供了对实际线程挂钟的访问,即。 the real CPU-time clock of the calling thread. The thread relative 可以通过调用 thread _ lock: : now ()获得当前时间

#include <boost/chrono/thread_clock.hpp>
{
...
using namespace boost::chrono;
thread_clock::time_point start = thread_clock::now();
...
thread_clock::time_point stop = thread_clock::now();
std::cout << "duration: " << duration_cast<milliseconds>(stop - start).count() << " ms\n";

这对于英特尔 Mac 10.7来说似乎很管用:

#include <time.h>


time_t start = time(NULL);




//Do your work




time_t end = time(NULL);
std::cout<<"Execution Time: "<< (double)(end-start)<<" Seconds"<<std::endl;

如果使用 c + + 11,这里有一个简单的包装器(参见 大意) :

#include <iostream>
#include <chrono>


class Timer
{
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const {
return std::chrono::duration_cast<second_>
(clock_::now() - beg_).count(); }


private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};

或者对于 * nix 上的 c + + 03:

#include <iostream>
#include <ctime>


class Timer
{
public:
Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }


double elapsed() {
clock_gettime(CLOCK_REALTIME, &end_);
return end_.tv_sec - beg_.tv_sec +
(end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
}


void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }


private:
timespec beg_, end_;
};

Example of usage:

int main()
{
Timer tmr;
double t = tmr.elapsed();
std::cout << t << std::endl;


tmr.reset();
t = tmr.elapsed();
std::cout << t << std::endl;
return 0;
}

如果你使用:

tstart = clock();


// ...do something...


tend = clock();

然后你需要以下几个步骤来计算时间:

time = (tend - tstart) / (double) CLOCKS_PER_SEC;

对我来说,最简单的方法是:

#include <boost/timer.hpp>


boost::timer t;
double duration;


t.restart();
/* DO SOMETHING HERE... */
duration = t.elapsed();


t.restart();
/* DO OTHER STUFF HERE... */
duration = t.elapsed();

使用这段代码,你不必做经典的 end - start

享受你最喜欢的方式。

I added this answer to clarify that the accepted 回答 shows CPU time which may not be the time you want. Because according to 参考文献, there are CPU time and wall clock time. Wall clock time is the time which shows the actual elapsed time regardless of any other conditions like CPU shared by other processes. For example, I used multiple processors to do a certain task and the CPU time was high 18s where it actually took 2 in actual wall clock time.

为了得到实际的时间,

#include <chrono>


auto t_start = std::chrono::high_resolution_clock::now();
// the work...
auto t_end = std::chrono::high_resolution_clock::now();


double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count();