我想花时间实现我编写的一些C++函数的性能。我如何获得以毫秒为单位的时间?毫秒计时C++
我知道如何通过
start=clock()
diff=(clock()-start)/(double) CLOCKS_PER_SEC
cout<<diff
我使用Ubuntu的Linux操作系统和g ++编译器得到的时间以秒计。
我想花时间实现我编写的一些C++函数的性能。我如何获得以毫秒为单位的时间?毫秒计时C++
我知道如何通过
start=clock()
diff=(clock()-start)/(double) CLOCKS_PER_SEC
cout<<diff
我使用Ubuntu的Linux操作系统和g ++编译器得到的时间以秒计。
在Linux中,请看clock_gettime()
。它基本上可以给你从任意点开始经过的时间,以纳秒为单位(对于你来说应该足够好)。
请注意,它是是由POSIX标准指定的,所以你应该在Unix派生的系统上使用它。
带有'CLOCK_PROCESS_CPUTIME_ID'的[clock_gettime()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html)将替代'clock()' – Cubbi
@Jerry Coffin你当然是对的,但是OP确实表示他们使用的是Linux,自1994年以来,它有CLOCK_PROCESS_CPUTIME_ID和CLOCK_THREAD_CPUTIME_ID。 – Cubbi
谢谢你飘渺! – smilingbuddha
Try diff =(clock() - start)* 1000.0/CLOCKS_PER_SEC;
这个想法是,你的时钟数乘以1000,所以,而之前,你可能会得到2(秒),你现在得到2000(毫秒)。
注:
在我的戴尔台式机,这是相当快...... 的Ubuntu在5210 bogomips峰值
时间(0)需要大约80毫微秒(2.4秒30万个电话)
时间(0)让我来衡量 clock_gettime(),这需要每个呼叫的约1.3 U型秒(220万3秒)
(我不记得有多少毫微秒每时间步长)
因此,通常情况下,我使用以下内容,约3秒的调用。
// ////////////////////////////////////////////////////////////////////////////
void measuring_something_duration()
...
uint64_t start_us = dtb::get_system_microsecond();
do_something_for_about_3_seconds()
uint64_t test_duration_us = dtb::get_system_microsecond() - start_us;
uint64_t test_duration_ms = test_duration_us/1000;
...
其中使用这些函数
// /////////////////////////////////////////////////////////////////////////////
uint64_t mynamespace::get_system_microsecond(void)
{
uint64_t total_ns = dtb::get_system_nanosecond(); // see below
uint64_t ret_val = total_ns/NSPUS; // NanoSecondsPerMicroSeconds
return(ret_val);
}
// /////////////////////////////////////////////////////////////////////////////
uint64_t mynamespace::get_system_nanosecond(void)
{
//struct timespec { __time_t tv_sec; long int tv_nsec; }; -- total 8 bytes
struct timespec ts;
// CLOCK_REALTIME - system wide real time clock
int status = clock_gettime(CLOCK_REALTIME, &ts);
dtb_assert(0 == status);
// to 8 byte from 4 byte
uint64_t uli_nsec = ts.tv_nsec;
uint64_t uli_sec = ts.tv_sec;
uint64_t total_ns = uli_nsec + (uli_sec * NSPS); // nano-seconds-per-second
return(total_ns);
}
记住链接-lrt
([在C或C++亚毫秒精确定时]的可能重复http://stackoverflow.com/questions/2904887/sub-millisecond-precision-timing-in-c-or-c) – phooji
最近有多少问题使用'clock()'来问这个问题令人印象深刻。要测量时间,你应该使用'gettimeofday()'或'clock_gettime()'。 –
^我认为有一个比gettimeofday(),clock_gettime()更新,更好的选择... ...由Ethereal在下面提到。我很惊讶gettimeofday()也在出路。 – Patrick87