C++ 如何计算C++中的时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/728068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate a time difference in C++
提问by Hyman BeNimble
What's the best way to calculate a time difference in C++? I'm timing the execution speed of a program, so I'm interested in milliseconds. Better yet, seconds.milliseconds..
在 C++ 中计算时差的最佳方法是什么?我正在计时程序的执行速度,所以我对毫秒感兴趣。更好的是,秒.毫秒..
The accepted answer works, but needs to include ctime or time.h as noted in the comments.
接受的答案有效,但需要包括 ctime 或 time.h,如评论中所述。
回答by bayda
See std::clock()
function.
见std::clock()
功能。
const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC;
If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not seconds ).
如果您想计算 self (而不是 user )的执行时间,最好在时钟滴答(而不是 seconds )中执行此操作。
EDIT:
responsible header files - <ctime>
or <time.h>
编辑:
负责任的头文件 -<ctime>
或<time.h>
回答by gongzhitaao
if you are using c++11, here is a simple wrapper (see this gist):
如果您使用的是 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_;
};
Or for c++03 on *nix:
或者对于 *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;
}
回答by Jeremy CD
I would seriously consider the use of Boost, particularly boost::posix_time::ptime and boost::posix_time::time_duration (at http://www.boost.org/doc/libs/1_38_0/doc/html/date_time/posix_time.html).
我会认真考虑使用 Boost,特别是 boost::posix_time::ptime 和 boost::posix_time::time_duration(在http://www.boost.org/doc/libs/1_38_0/doc/html/date_time/posix_time .html)。
It's cross-platform, easy to use, and in my experience provides the highest level of time resolution an operating system provides. Possibly also very important; it provides some very nice IO operators.
它是跨平台的,易于使用,并且根据我的经验,它提供了操作系统提供的最高级别的时间分辨率。可能也很重要;它提供了一些非常好的 IO 操作符。
To use it to calculate the difference in program execution (to microseconds; probably overkill), it would look something like this [browser written, not tested]:
要使用它来计算程序执行的差异(到微秒;可能是矫枉过正),它看起来像这样[浏览器编写,未测试]:
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';
回答by Ultraviolet
I added this answer to clarify that the accepted answershows CPU time which may not be the time you want. Because according to the reference, 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 18swhere it actually took 2sin actual wall clock time.
我添加了这个答案以澄清接受的答案显示 CPU 时间,这可能不是您想要的时间。因为根据参考,有CPU时间和挂钟时间。挂钟时间是显示实际经过时间的时间,而不考虑其他进程共享的 CPU 等任何其他条件。例如,我使用多个处理器来完成某项任务,CPU 时间高达18秒,而实际挂钟时间实际上需要2 秒。
To get the actual time you do,
为了得到你做的实际时间,
#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();
回答by Gabi Davar
boost 1.46.0 and up includes the Chronolibrary:
boost 1.46.0 及更高版本包括Chrono库:
thread_clock class provides access to the real thread wall-clock, i.e. the real CPU-time clock of the calling thread. The thread relative current time can be obtained by calling thread_clock::now()
thread_clock 类提供对真实线程挂钟的访问,即调用线程的真实 CPU 时间时钟。线程相对当前时间可以通过调用thread_clock::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";
回答by aJ.
In Windows: use GetTickCount
在 Windows 中:使用GetTickCount
//GetTickCount defintition
#include <windows.h>
int main()
{
DWORD dw1 = GetTickCount();
//Do something
DWORD dw2 = GetTickCount();
cout<<"Time difference is "<<(dw2-dw1)<<" milliSeconds"<<endl;
}
回答by aJ.
You can also use the clock_gettime. This method can be used to measure:
您还可以使用clock_gettime。该方法可用于测量:
- System wide real-time clock
- System wide monotonic clock
- Per Process CPU time
- Per process Thread CPU time
- 全系统实时时钟
- 系统范围的单调时钟
- 每进程 CPU 时间
- 每进程线程 CPU 时间
Code is as follows:
代码如下:
#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";
}
`
`
回答by fengshaun
just in case you are on Unix, you can use time
to get the execution time:
以防万一您使用的是 Unix,您可以使用它time
来获取执行时间:
$ g++ myprog.cpp -o myprog
$ time ./myprog
回答by v3.
Just a side note: if you're running on Windows, and you really really need precision, you can use QueryPerformanceCounter. It gives you time in (potentially) nanoseconds.
附带说明:如果您在 Windows 上运行,并且确实需要精度,则可以使用QueryPerformanceCounter。它为您提供(可能)纳秒的时间。
回答by Jared Oberhaus
Get the system time in milliseconds at the beginning, and again at the end, and subtract.
在开始时以毫秒为单位获取系统时间,并在结束时再次减去。
To get the number of milliseconds since 1970 in POSIX you would write:
要在 POSIX 中获取自 1970 年以来的毫秒数,您可以编写:
struct timeval tv;
gettimeofday(&tv, NULL);
return ((((unsigned long long)tv.tv_sec) * 1000) +
(((unsigned long long)tv.tv_usec) / 1000));
To get the number of milliseconds since 1601 on Windows you would write:
要在 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);
If you cared to normalize the Windows answer so that it also returned the number of milliseconds since 1970, then you would have to adjust your answer by 11644473600000 milliseconds. But that isn't necessary if all you care about is the elapsed time.
如果您想标准化 Windows 答案,以便它也返回自 1970 年以来的毫秒数,那么您必须将答案调整 11644473600000 毫秒。但是,如果您只关心经过的时间,那就没有必要了。