在C ++中计算时差的最佳方法是什么?我正在计时程序的执行速度,所以我对毫秒感兴趣。更好的是秒。毫秒
可接受的答案有效,但需要包含ctime或time.h(如注释中所述)。
在C ++中计算时差的最佳方法是什么?我正在计时程序的执行速度,所以我对毫秒感兴趣。更好的是秒。毫秒
可接受的答案有效,但需要包含ctime或time.h(如注释中所述)。
Answers:
参见std::clock()
功能。
const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC;
如果要计算自身的执行时间(而不是用户的执行时间),则最好以时钟滴答(而不是秒)为单位。
编辑:
负责的头文件- <ctime>
或<time.h>
clock()
返回程序消耗的CPU时间。因此,如果程序并行运行,则函数返回的时间将是所有CPU所用时间的累积,而不是经过的时间 cplusplus.com/reference/ctime/clock
如果您使用的是c ++ 11,则这是一个简单的包装器(请参见this gist):
#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_;
};
用法示例:
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;
}
Timer()
和对elapsed()
if 的呼叫之间的时间,则此方法将不起作用!std::chrono::high_resolution_clock::is_steady
-在Linux上就是这种情况!
我会认真考虑使用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)。
它是跨平台的,易于使用,以我的经验,它提供了操作系统提供的最高级别的时间分辨率。可能也很重要;它提供了一些非常不错的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';
我添加了此答案以澄清接受的答案显示的CPU时间可能不是您想要的时间。因为根据参考,有CPU时间和挂钟时间。挂钟时间是显示实际经过时间的时间,而与其他进程共享的CPU等其他条件无关。例如,我使用多个处理器来完成某项任务,而CPU时间则高达18 秒,而实际挂钟时间实际上为2秒。
要获取您的实际时间,
#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();
Boost 1.46.0及更高版本包含Chrono库:
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";
std::chrono
几乎相同内容的名称空间。
在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;
}
您也可以使用clock_gettime。此方法可用于测量:
代码如下:
#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";
}
`
附带说明:如果您在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毫秒。但这不是必需的,只要您关心的只是经过的时间即可。