放一些常见函数/方法的测速结果。本地测的。通常情况下会采取一些防优化策略。通常情况下是 VS2022 实现,如果有不同的会加以说明。
C++ VS C
fill VS memset VS 循环赋值
测速程序(段):
unsigned char arr[100000005];
int main()
{
auto ss = chrono::high_resolution_clock::now().time_since_epoch().count();
unsigned long long mul = 1;
for (int i = 1; i <= 100; i++)
{
// fill:
// fill(arr + 1, arr + (100000002 - i), i);
// memset:
// memset(arr + 1, 0, sizeof(char) * (100000001 - i));
// 循环赋值:
// for(int j=1;j<=100000001 - i;j++)
// {
// arr[j] = i;
// }
unsigned xs = 0;
for (int j = 1; j <= 100000000; j++)
{
xs ^= arr[j];
}
mul *= (xs == 0 ? 114514 : xs);
}
auto tt = chrono::high_resolution_clock::now().time_since_epoch().count();
printf("mul = %llu, time = %Lf\n", mul, 1.0L * (tt - ss) * chrono::high_resolution_clock::period::num / chrono::high_resolution_clock::period::den);
return 0;
}Debug 测速结果:fill ,memset ,循环赋值 。
Release 测速结果:fill ,memset ,循环赋值 。
结论:首先 Release 一如既往地强。STL fill 最快,而手动循环最慢。别再用又难写又慢的手动赋值啦!
C++ VS 手写
fill VS memset VS 循环赋值
见 C++ VS C 中的同标题部分。
C++ 完胜。
iota VS 循环赋值
测速程序(段):
unsigned char arr[100000005];
int main()
{
auto ss = chrono::high_resolution_clock::now().time_since_epoch().count();
unsigned long long mul = 1;
for (int i = 1; i <= 100; i++)
{
// iota:
// iota(arr + 1, arr + (100000002 - i), i); // iota 常用于并查集初始化。
// 循环赋值:
// for(int j=1;j<=100000001 - i;j++)
// {
// arr[j] = i + j - 1;
// }
unsigned xs = 0;
for (int j = 1; j <= 100000000; j++)
{
xs ^= arr[j];
}
mul *= (xs == 0 ? 114514 : xs);
}
auto tt = chrono::high_resolution_clock::now().time_since_epoch().count();
printf("mul = %llu, time = %Lf\n", mul, 1.0L * (tt - ss) * chrono::high_resolution_clock::period::num / chrono::high_resolution_clock::period::den);
return 0;
}Debug 测速结果:iota ,循环赋值 。
Release 测速结果:iota ,循环赋值 。
结论:在 Debug 下循环赋值快一些,而 Release 下 iota 相对较快。可以根据是否优化选择使用哪种。
C VS 手写
fill VS memset VS 循环赋值
见 C++ VS C 中的同标题部分。
C 完胜。