http://blog.csdn.net/weiffun/article/details/4307852
在程序设计和优化过程中,我们通常希望能有工具帮助我们分析热点代码、覆盖率、内存泄露等这些特性,对多线程程序还希望能分析并发性、竞争和死锁等等。但这些特征通常在静态编译时很难获取,而且往往只能在运行时才能确定。Pin是intel开发的动态插桩工具,它提供一套API让我们开发和定制自己的性能分析工具,此外它还被广泛用在体系结构研究、安全等领域。目前intel parallel studio的很多特性便是基于pin开发而成。
Pin的工作机制
目前对程序进行剖析(profiling),主要有二种方法:统计硬件计数器和插桩。Pin采用了插装技术,在程序的执行过程中动态插入分析代码。下面的代码片段演示了插装的过程,假设我们要统计程序执行的指令数,可以在程序每执行一条指令时,插入一条count++语句,当程序执行完时,count的值就是程序执行的指令数。
- count++
- sub $0xff, %edx
- count++
- cmp %esi, %edx
- count++
- jle <L1>
- count++
- mov $0x1, %edi
- count++
- add $0x10, %eax
Pin是采用动态编译技术实现动态插装,将分析代码和被分析程序动态编译后放置到代码缓存,然后由cpu动态执行代码缓存里的代码。
利用pin统计程序执行的指令数
- #include <iostream>
- #include <fstream>
- #include "pin.H"
-
-
-
- static UINT64 icount = 0;
-
-
- VOID docount() { icount++; }
-
-
- VOID Instruction(INS ins, VOID *v)
- {
-
- INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)docount, IARG_END);
- }
-
- KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool",
- "o", "inscount.out", "specify output file name");
-
-
- VOID Fini(INT32 code, VOID *v)
- {
-
- ofstream OutFile;
- OutFile.open(KnobOutputFile.Value().c_str());
- OutFile.setf(<a href="http://lib.csdn.net/base/ios" class='replace_word' title="iOS知识库" target='_blank' style='color:#df3434; font-weight:bold;'>iOS</a>::showbase);
- OutFile << "Count " << icount << endl;
- OutFile.close();
- }
-
-
- int main(int argc, char * argv[])
- {
-
- PIN_Init(argc, argv);
-
-
- INS_AddInstrumentFunction(Instruction, 0);
-
-
- PIN_AddFiniFunction(Fini, 0);
-
-
- PIN_StartProgram();
-
- return 0;
- }
注释比较详细,很容易看懂
Pin主页:http://www.pintool.org
https://software.intel.com/en-us/articles/pintool-downloads