SLP(Chapter 10 part 1):性能评估 / 性能测试
1 基础知识
性能优化对象:瓶颈 bottleneck / Hot spot(需要很长时间执行的代码段)
优化过程
2 Performance Principles (法则)
2.1 80/20定律 (Pareto Principle)
80%的CPU时间花在20%的代码上
Amdahl定律 -
- 用于查找对系统整体性能提声最大的部分优化。
- 用于算并行计算的最大加速比
部分优化E使一个运行时间为P的部分加速S倍,其他部分速度不变
整体加速比 = 优化前的时间 / 优化后的时间 = 1 / ((1-P)+ P/S)
3 Performance Measurement 性能评估 / 测试(对时间)
3.1 计时级制 Timing mechanism
(1)Time时间
时间用于:测量事件序列;量化事件的持续时间和间隔
Why 在计算机系统中需要时间?
- 硬件、操作系统都需要时间和计时器。
- 衡量程序性能,如执行时间
计算机系统里的两种时间
- Wall time:运行特定程序所需的总时间。(包含空闲等与用于进程无关的时间)
- CPU时间
User CPU time + System CPU time = CPU time
时间片 time slice
时钟单元,在某状态的最小停留时间
(2)Timer 计时器
硬件/软件都有,用于测量时间
硬件中(如 Intel Architecture, 32/X86, 8253)
- RTC(Real Time CMOS Clock,实时时钟/外部晶振实时时钟)
- CMOS RAM:存储时间、配置
- 低功率电池
- 用于启动过程
- 后台一直刷新
- 物理原理:晶体震荡产生时钟频率
== 主频 main frequency / 时钟频率 Clock frequency:每秒周期数的倒数==
- PIT (Programmable Interval Timer 可编程间隔定 时器)
计数器生成输出信号,可能会触发中断 - PIC (Programmable Interrupt Controller,中断控制器)
- TSC (Time Stamp Counter 时间戳计数器)
- TSC从RTC收到CLK signal
- 是64位寄存器,计算周期数(使用longlong)
- 使用RDTSC访问寄存器的值(纳秒级访问)
- Windows中的接口,QueryPerformanceFrequency / QueryPerformanceCounter访问(微秒级访问)参数是一个64位整型的地址
OS中(如 Windows, GetTickCount() | Linux, jiffies )
- DWORD GetTickCount(void); //自上次启动系统以来经过的毫秒数,每 49.7 天循环一次
从 RTC 读取,然后转换 - 系统时间:参数是SYSTEMTIME类型的地址
GetLocalTime() //当地时间
GetSystemTime() //格林威治时间 - 生存期:参数是LARGE_INTERGER(64bits)的地址,用成员QuadPart访问值
GetSystemTimeAsFileTime()
Win - 1601.1.1 | Linux – 1970.1.1
C/C++(如C的<time.h>)
==Macro宏 CLOCKS_PER_SEC = 1000 ==
- clock()返回的单位是ms,需要除以CLOCK_PER_SECOND得到s
- localtime / gmtime: 参数是time_t,返回值是struct tm类型指针,转换为本地时间,或格林威治时间
用asctime函数将其返回值转换成字符串输出 - time_t, clock_t都是long
- struct tm
Statistical sampling (抽样统计) / Profiling (分析)
对采样过程使用概率定律测量程序状态。
计时器定期中断程序,并且记录程序计数器
- 估计程序在程序中花费的时间
- 检查程序是否将大部分时间花费在几个位置
优点:节约时间、成本很低
缺点:可能不能检查到所有风险
4 Profiler (评测器)
软件探查器 Software profiler
一种程序,用于对一个或多个过程代码的执行进行基准测试,以帮助用户了解在代码执行方面花费的时间。
GNU Gprof – Linux
Vtune - Intel
Visual C++ profiler
Valgrind for different platforms
Profiler用于:
帮助程序员识别
• 计划的哪些部分是瓶颈导致缓慢。• 代码的哪些部分被调用的频率高。
MFLOPS: million floating point operations巨型浮点操作
性能可能用:每秒的MFLOPS数衡量