如何对 C++ 代码的性能进行基准测试?

2023-06-04C/C++开发问题
0

本文介绍了如何对 C++ 代码的性能进行基准测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我开始认真地研究算法和数据结构,并且有兴趣学习如何比较实现 A&DT 的不同方式的性能.

I am starting to study algorithms and data structures seriously, and interested in learning how to compare the performance of the different ways I can implement A&DTs.

对于简单的测试,我可以获取某件事运行之前/之后的时间,运行那件事 10^5 次,然后平均运行时间.我可以按大小参数化输入,或对随机输入进行抽样,并获得运行时间与输入大小的列表.我可以将其输出为 csv 文件,然后将其输入到 Pandas 中.

For simple tests, I can get the time before/after something runs, run that thing 10^5 times, and average the running times. I can parametrize input by size, or sample random input, and get a list of running times vs. input size. I can output that as a csv file, and feed it into pandas.

我不确定是否有任何警告.我也不知道如何衡量空间复杂度.

I am not sure there are no caveats. I am also not sure what to do about measuring space complexity.

我正在学习用 C++ 编程.是否有人性化的工具来实现我的目标?

I am learning to program in C++. Are there humane tools to achieve what I am trying to do?

推荐答案

对代码进行基准测试并不容易.我发现最有用的是 Google 基准库. 即使您不打算使用它,它也可能是很高兴阅读一些例子.它有很多可能性来参数化测试,将结果输出到文件,甚至返回算法的大 O 符号复杂度(仅举几个例子).如果您熟悉 Google 测试框架,我建议您使用它.它还使编译器优化成为可能,因此您可以确保您的代码没有被优化掉.

Benchmarking code is not easy. What I found most useful was Google benchmark library. Even if you are not planning to use it, it might be good to read some of examples. It has a lot of possibilities to parametrize test, output results to file and even returning you Big O notation complexity of your algorithm (to name just few of them). If you are any familiar with Google test framework I would recommend you to use it. It also keeps compiler optimization possible to manage so you can be sure that your code wasn't optimized away.

在 CppCon 2015: Chandler Carruth "Tuning C++: Benchmarks,和 CPU 和编译器!天哪!".您可能犯的错误有很多见解(它还使用谷歌基准)

There is also great talk about benchmarking code on CppCon 2015: Chandler Carruth "Tuning C++: Benchmarks, and CPUs, and Compilers! Oh My!". There are many insights in possible mistake that you can make (it also uses google benchmark)

这篇关于如何对 C++ 代码的性能进行基准测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6