你有什么建议来优化从毫秒msecsOut
到9位别名iX: 8H 7H 6M 5M 4S 3S 2MS 1MS 0MS
的转换,假设循环是一个给定的约束,模数可能不是最理想的,到目前为止我有:
(我们正在使用XILINX的Spartan-3 FPGA系列上的systemc进行编程)
int msecsOut = 1234123412;
// iX: 8H 7H 6M 5M 4S 3S 2MS 1MS 0MS
for (int i = 8; i >= 0; --i) {
int digitOut = -1;
if (i == 8) {
digitOut = msecsOut / (1000 * 60 * 60 * 10);
msecsOut = msecsOut % (1000 * 60 * 60 * 10);
} else if (i == 7) {
digitOut = msecsOut / (1000 * 60 * 60);
msecsOut = msecsOut % (1000 * 60 * 60);
} else if (i == 6) {
digitOut = msecsOut / (1000 * 60 * 10);
msecsOut = msecsOut % (1000 * 60 * 10);
} else if (i == 5) {
digitOut = msecsOut / (1000 * 60);
msecsOut = msecsOut % (1000 * 60);
} else if (i == 4) {
digitOut = msecsOut / (1000 * 10);
msecsOut = msecsOut % (1000 * 10);
} else if (i == 3) {
digitOut = msecsOut / (1000);
msecsOut = msecsOut % (1000);
} else if (i == 2) {
digitOut = msecsOut / (100);
msecsOut = msecsOut % (100);
} else if (i == 1) {
digitOut = msecsOut / (10);
msecsOut = msecsOut % (10);
} else if (i == 0) {
digitOut = msecsOut / (1);
}
cout << digitOut << " ";//debug only
}
cout<<endl;//debug only
答案 0 :(得分:2)
您可以通过使用数组
来摆脱测试i
(这会使您的循环失效)
int msecsOut = 1234123412;
const int factors[] = {
1000 * 60 * 60 * 10,
1000 * 60 * 60,
1000 * 60 * 10,
1000 * 60,
1000,
100,
10
};
const char* symbols[] = {"H", "H", "M", "M", "S", "S", "MS", "MS"};
// iX: 8H 7H 6M 5M 4S 3S 2MS 1MS 0MS
for (int i = 0; i != sizeof(factors) / sizeof(*factors); ++i) {
const int digitOut = msecsOut / factors[i];
msecsOut = msecsOut % factors[i];
std::cout << digitOut << symbols[i] << " ";
}
std::cout << msecsOut << "MS" << std::endl;