工欲善其事,必先利其器。为了优化代码,我们需要准确的获取代码在运行期间的相关数据,比如最重要的运行时间。这里介绍若干种测量方法。
目前有不少商业软件可以完成类似的测试,比如Intel VTune,AMD CodeAnalyst等等。VS2005的Professional版本中也有相应的Profiling功能。不过,对于轻量级的代码优化而言,杀鸡未必要用牛刀。
首先,对于简单的计时需求,可以使用boost的timer类,它内部使用clock函数。如果觉得精度仍然不够的话,可以使用下面的CTimingLight类
#include <windows.h>
enum TimerType {e_TimerType_Accurate};
template<TimerType Type>
struct TimerTimeFormat {};
template<>
struct TimerTimeFormat<e_TimerType_Accurate> {
typedef LARGE_INTEGER TimeFormat;
TimeFormat StartTime;
const double Frequency;
TimerTimeFormat():Frequency(GetFrequency().LowPart) {}
void SetS
目前有不少商业软件可以完成类似的测试,比如Intel VTune,AMD CodeAnalyst等等。VS2005的Professional版本中也有相应的Profiling功能。不过,对于轻量级的代码优化而言,杀鸡未必要用牛刀。
首先,对于简单的计时需求,可以使用boost的timer类,它内部使用clock函数。如果觉得精度仍然不够的话,可以使用下面的CTimingLight类
#include <windows.h>
enum TimerType {e_TimerType_Accurate};
template<TimerType Type>
struct TimerTimeFormat {};
template<>
struct TimerTimeFormat<e_TimerType_Accurate> {
typedef LARGE_INTEGER TimeFormat;
TimeFormat StartTime;
const double Frequency;
TimerTimeFormat():Frequency(GetFrequency().LowPart) {}
void SetS

本文介绍了如何精确测量代码的CPU运行周期,包括使用boost库的timer类、CTimingLight模板类以及Agner Fog的testp库。通过这些工具,可以获取代码运行时间、CPU时钟、缓存缺失等信息,进行代码优化。注意testp库可能需要管理员权限,并且不适合测试长时间运行的代码。
最低0.47元/天 解锁文章
3986

被折叠的 条评论
为什么被折叠?



