我需要將 int 值 1、2、3 映射到字符 'C'、'M'、'A'
最快的方法是什么(這將被稱為每秒 100 次 24/7)?
一個宏或一個行內函式和一堆 ?: 運算子或 ifs 或 switch?還是一個陣列?
uj5u.com熱心網友回復:
查找表似乎是最明顯的方法,因為它也是無分支的:
constexpr char map(std::size_t i) {
constexpr char table[] = "0CMA";
// if in doubt add bounds checking for i, but it will cost performance
return table[i];
}
通過優化觀察,查找表歸結為一個整數常量。
編輯:如果你沒有我那么懶惰,你可以減少額外的指令,并因此指定查找表:
constexpr char table[] = {0, 'M', 'C', 'A'};
uj5u.com熱心網友回復:
我的建議:(char)(0x414D4300 >> (i * 8))
你可以寫而不是 0x414D4300 (('C' << 8) | ('M' << 16) | ('A' << 24))。
只有實際測驗會告訴您這是否比位掩碼的答案更快。
如果它每秒只運行 100 次,那么無論如何你都是在追逐紅鯡魚。即使您以最愚蠢的方式撰寫此部分,它似乎也比您的程式的其余部分快一百萬倍。
uj5u.com熱心網友回復:
你過早地優化你的代碼。讓我證明一下。這是仍然合理的最天真,最慢的方法:
#include <map>
char map(int i) {
std::map<int, char> table;
table[1] = 'C';
table[2] = 'M';
table[3] = 'A';
return table[i];
}
它生成 數百行匯編指令。
讓我們為一百萬個元素計時:
#include <iostream>
#include <map>
#include <chrono>
#include <cstdlib>
#include <vector>
char map(int i) {
std::map<int, char> table;
table[1] = 'C';
table[2] = 'M';
table[3] = 'A';
return table[i];
}
int main() {
int const count = 1'000'000;
std::vector<int> elms(count);
std::srand(0); // I know that rand is no good, but it's OK for this example
for (int i = 0; i < count; i) {
elms[i] = std::rand() % 3 1;
}
auto beg = std::chrono::high_resolution_clock::now();
volatile int do_not_optimize;
for (int i = 0; i < count; i) {
do_not_optimize = map(elms[i]);
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - beg);
std::cout << "Duration: " << duration.count() << " ms" << std::endl;
}
這是我的計算機上的輸出,其中有許多其他程式同時運行:
Duration: 246 ms
This terrible implementation under terrible conditions still meets your needs 40'650x over. I bet you have way more to worry about elsewhere in your codebase. Remember to make it right, then make it fast only if it's not already fast enough.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/454352.html
