(all code comes from https://github.com/llvm/llvm-project.git)
Timer
利用LLVM Timer计时器可以比较方便地统计 时间消耗。其数据结果和函数主要定义在
Timer.h 和Timer.cpp文件中
注意
1 Timer 在析构的时候打印统计时间
2 由于Timer计时器本身也有时间开销,所以谨慎在 高频率 的循环 中使用它。
下面举两个例子:
该例子通过在 llvm codegenprepare pass中增加Timer计时器来 统计该pass中代码段的执行时间。
用例 1 在 CodeGenPrepare::runOnFunction 中增加计时器
diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 6778af22f532..a9caa802c3d5 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -99,6 +99,8 @@
#include <memory>
#include <utility>
#include <vector>
+#include "llvm/Support/Timer.h" // 添加计时器头文件
。。。
bool CodeGenPrepare::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
+ Timer T1("T1", F.getName());
+ T1.startTimer();
// 通过将函数名写入 计时器 的描述信息,可以省略掉下面的LLVM_DEBUG,这样就不用-debug来编译了。
// LLVM_DEBUG(dbgs() << "code generation zxzx: " << F.getName() <<"\n");
。。。
+ T1.stopTimer();
return EverMadeChange;
}
用例 2 在 CodeGenPrepare类中 增加 “全局” 计时器指针。
有时候我们会 及时 其它函数体内的 代码时间,将计时器作为参数传递到 子函数很不方便,
于是我们在 CodeGenPrepare类 中增加 计时器 指针。 让后在主函数 runOnFunction 分配一个
计时器对象,并在 末尾 释放它。
4 +++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
5 @@ -99,6 +99,8 @@
6 #include <memory>
7 #include <utility>
8 #include <vector>
9 +#include <iostream>
10 +#include "llvm/Support/Timer.h"
11
12 using namespace llvm;
13 using namespace llvm::PatternMatch;
14 class CodeGenPrepare;
15 public:
18 + Timer *Tptr =nullptr; // 在CodeGenPrepare类中定义一个Timer指针
20 。。。
21 }
24 bool CodeGenPrepare::runOnFunction(Function &F) {
30 + Tptr = new Timer("T2", "desc"); // 分配一个计时器
31 。。。
41 + delete Tptr; // 释放掉Timer (Timer释放时打印时间)
42 + Tptr = nullptr;
43 return EverMadeChange;
44 }
45
// 在子函数中直接使用 计时器指针
46 @@ -8055,11 +8068,15 @@ bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
。。。
50 + Tptr->startTimer();
51 while (CurInstIterator != BB.end()) {
52 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
53 - if (ModifiedDT)
54 + if (ModifiedDT) {
55 + Tptr->stopTimer(); // 堵住所有出口 (startTimer 和 stopTimer 必须封闭)
56 return true;
57 + }
58 }
59 + Tptr->stopTimer();
60
}