我想花時間實現我編寫的一些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