[英]uint32_t vs std::string comparison of IpV4 - performance
在比較 ip 地址時,我假設字符串的比較比比較 uin32_t 慢得多。 由於避免了我的代碼有時更復雜且可讀性更低。 但是,我開始想知道真正的區別是什么,並決定進行快速基准測試。 結果讓我吃驚。 比較字符串結果證明這兩種方法具有相同的速度。 現在我不確定我是否過度簡化了測試或做錯了什么。 如果不是,為什么幾乎沒有區別? 比較 uint32_t 與 uint32_t 次 x 不應該相等。
static void IntIpV4Comparation(benchmark::State& state) {
// Code inside this loop is measured repeatedly
uint32_t ip1 = 100;
uint32_t ip2 = 200;
for (auto _ : state) {
bool areEqual = ip1 == ip2;
}
}
// Register the function as a benchmark
BENCHMARK(IntIpV4Comparation);
static void StringIpV4Comparation(benchmark::State& state) {
// Code before the loop is not measured
std::string ip1 = "127.0.0.1";
std::string ip2 = "127.0.0.2";
for (auto _ : state) {
bool areEqual = ip1 == ip2;
}
}
BENCHMARK(StringIpV4Comparation);
正如預期的那樣,不同之處還在於 char 使字符串不相等的地方。 當它在中間時,結果是相反的(但差異仍然很小)。 差異可能最大的邊緣情況是什么?
只是為了從未回答的問題隊列中解決這個問題......
您觀察到的時間是相同的,因為在以下循環中,編譯器會優化測試,因為從未使用過areEqual
值:
for (auto _ : state) {
bool areEqual = ip1 == ip2;
}
在 Google Benchmark 中,您可以使用benchmark::DoNotOptimize()
防止這種情況發生:
for (auto _ : state) {
bool areEqual = ip1 == ip2;
benchmark::DoNotOptimize(areEqual);
}
現在可以看出區別:
(測試在quick-bench 上優化的另一個線索。com是空的“生成的程序集”輸出)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.