![](/img/trans.png)
[英]Weird result with std::chrono::duration_cast for 1 second and 2 second
[英]std::chrono::duration_cast - any unit more precise than nano-second?
我想問一下,如何計算皮秒,飛秒和更高精度等任何單位的時間。 我正在計算函數的運行時間並使用納秒,當我使用毫秒或納秒時,函數的運行時間返回0。 我認為Chrono庫只支持納秒,這是我在鍵入chrono后按ctrl + space時出現的最精確的::
int main()
{
auto t1 = std::chrono::high_resolution_clock::now();
f();
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "f() took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()
<< " milliseconds\n";
}
代碼來源: http : //en.cppreference.com/w/cpp/chrono/duration/duration_cast
謝謝。
你可以用更精確的持續時間計算時間(皮秒......)
www.stroustrup.com/C++11FAQ.html
請參閱以下定義:
typedef ratio<1, 1000000000000> pico;
然后使用:
duration<double, pico> d{1.23}; //...1.23 picoseconds
更新您的問題有三個部分:
上面我部分回答了第一個問題(如何定義“皮秒”持續時間)。 請考慮以下代碼作為示例:
#include <chrono>
#include <iostream>
#include <typeinfo>
using namespace std;
using namespace std::chrono;
void f()
{
enum { max_count = 10000 };
cout << '|';
for(volatile size_t count = 0; count != max_count; ++count)
{
if(!(count % (max_count / 10)))
cout << '.';
}
cout << "|\n";
}
int main()
{
typedef std::ratio<1l, 1000000000000l> pico;
typedef duration<long long, pico> picoseconds;
typedef std::ratio<1l, 1000000l> micro;
typedef duration<long long, micro> microseconds;
const auto t1 = high_resolution_clock::now();
enum { number_of_test_cycles = 10 };
for(size_t count = 0; count != number_of_test_cycles; ++count)
{
f();
}
const auto t2 = high_resolution_clock::now();
cout << number_of_test_cycles << " times f() took:\n"
<< duration_cast<milliseconds>(t2 - t1).count() << " milliseconds\n"
<< duration_cast<microseconds>(t2 - t1).count() << " microseconds\n"
<< duration_cast<picoseconds>(t2 - t1).count() << " picoseconds\n";
}
它產生這個輸出:
$ ./test
|..........|
|..........|
|..........|
|..........|
|..........|
|..........|
|..........|
|..........|
|..........|
|..........|
10 times f() took:
1 milliseconds
1084 microseconds
1084000000 picoseconds
如你所見,為了獲得1毫秒的結果,我不得不重復f()10次。 當計時器沒有足夠的精度時,重復測試是一種常規方法。 有一個問題與重復有關 - 重復你的測試N次不需要花費一定比例的時間。 你需要先證明它。
另一件事 - 雖然我可以使用皮秒持續時間進行計算,但我的high_resolution_timer不能給出比微秒更高的精度。
要獲得更高的精度,您可以使用時間戳計數器,請參閱wiki / Time_Stamp_Counter - 但這很棘手並且特定於平台。
“標准”PC的分辨率大約為100納秒,因此除非您擁有某種自定義硬件,否則嘗試以高於此值的分辨率測量時間是不可能的。 請參閱現代PC的內部時鍾精確程度如何? 有關問題,請查看第二個答案: https : //stackoverflow.com/a/2615977/1169863 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.