#include <stdlib.h>
///////////////////
bool runtimeIsPalindrome(const char* s, int len)
{
if(len < 2)
return true;
else
return s[0] == s[len-1] && runtimeIsPalindrome(&s[1], len-2);
}
///////////////////
constexpr bool compileTimeIsPalindrome(const char* s, int len)
{
return len < 2 ? true : s[0] == s[len-1] && compileTimeIsPalindrome(&s[1], len-2);
}
///////////////////
int main()
{
constexpr char c[] = "helloworlddlrowolleh";
for(size_t nn=0;nn<1e8; ++nn) {
// static_assert(compileTimeIsPalindrome(c, sizeof(c)-1 ), "Blah");
// compileTimeIsPalindrome(c, sizeof(c)-1 );
// runtimeIsPalindrome( c, sizeof(c)-1 );
}
}
与版本...runtimeIsPalindrome
与版本...
clear; g++ -std=c++11 plaindrome.cpp; time ./a.out
real 0m8.333s
user 0m8.322s
sys 0m0.005s
...但是使用
compileTimeIsPalindrome
版本,我实际上似乎观察到一些编译时的魔术...
clear; g++ -std=c++11 plaindrome.cpp; time ./a.out
real 0m8.257s
user 0m8.247s
sys 0m0.004s
为什么在此示例中尝试断言时,汇编时间评估才能起作用?
注:在此示例中进行任何优化的分析似乎毫无意义,因为在循环中调用的函数中,结果似乎是恒定的,从而给出了与上面最快的轮廓时间相似的时间。
static_assert(compileTimeIsPalindrome
不能保证编译时间评估,除非在clear; g++ -std=c++11 plaindrome.cpp; time ./a.out
real 0m0.265s
user 0m0.263s
sys 0m0.001s
constexpr