#include <chrono>
#include <iostream>
constexpr auto strlen_1(char const* sz) {
auto const* p = sz;
while (*p) {
++p;
}
return p - sz;
}
consteval auto strlen_2(char const* sz) {
auto const* p = sz;
while (*p) {
++p;
}
return p - sz;
}
int main() {
using Clock = std::chrono::steady_clock;
using Ms = std::chrono::milliseconds;
using std::chrono::duration_cast;
auto n = 0;
auto start = Clock::now();
{
for (auto i = 0; i < 1000 * 10000; ++i) {
n += strlen_1("abcdefghijklmnopqrstuvwxyz");
}
}
auto stop = Clock::now();
auto elapsed = duration_cast<Ms>(stop - start).count();
std::cout << "strlen_1: " << elapsed << "ms" << std::endl;
n = 0;
start = Clock::now();
{
for (auto i = 0; i < 1000 * 10000; ++i) {
n += strlen_2("abcdefghijklmnopqrstuvwxyz");
}
}
stop = Clock::now();
elapsed = duration_cast<Ms>(stop - start).count();
std::cout << "strlen_2: " << elapsed << "ms" << std::endl;
return n;
}
输出是:
strlen_1: 435ms
strlen_2: 18ms
见https://godbolt.org/z/zMTq64MME
显然,strlen_1
不在编译时计算,而在编译时计算strlen_2
。
为什么 constexpr
不在编译时计算字符串文字?