跳到正文

科技·工程

C++ Speed test

SClan_Official约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月10日
篇幅
约 4 分钟

版本

  1. v1当前

放一些常见函数/方法的测速结果。本地测的。通常情况下会采取一些防优化策略。通常情况下是 VS2022 实现,如果有不同的会加以说明。

C++ VS C

fill VS memset VS 循环赋值

测速程序(段):

C++
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 17.443320s17.443320\mathrm{s},memset 19.853638s19.853638\mathrm{s},循环赋值 38.772942s38.772942\mathrm{s}。

Release 测速结果:fill 2.442624s2.442624\mathrm{s},memset 2.572445s2.572445\mathrm{s},循环赋值 2.987492s2.987492\mathrm{s}。

结论:首先 Release 一如既往地强。STL fill 最快,而手动循环最慢。别再用又难写又慢的手动赋值啦!

C++ VS 手写

fill VS memset VS 循环赋值

见 C++ VS C 中的同标题部分。

C++ 完胜。

iota VS 循环赋值

测速程序(段):

C++
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 43.420758s43.420758\mathrm{s},循环赋值 38.460369s38.460369\mathrm{s}。

Release 测速结果:iota 7.309839s7.309839\mathrm{s},循环赋值 9.463720s9.463720\mathrm{s}。

结论:在 Debug 下循环赋值快一些,而 Release 下 iota 相对较快。可以根据是否优化选择使用哪种。

C VS 手写

fill VS memset VS 循环赋值

见 C++ VS C 中的同标题部分。

C 完胜。

原文