为了节省时间,本文使用彩云小译机翻,原文出处:
The RDTSC Performance Timer written in C++
RDTSC 是 IA-32/IA-64(或 x86/x64)指令,它将处理器时间戳的当前值加载到 EDX: EAX 寄存器中。RDTSC 是“阅读时间戳计数器”("Read Time-Stamp Counter")的缩写。它返回自上次复位以来的时钟周期数。
现代编译器 Visual Studio 已经实现了编译器的内部特性,因此您不必手动将汇编操作码或助记符(RDTSC)插入到 c + + 源代码中。我们可以用它作为一个性能基准(定时器)来衡量不同程序的执行情况,例如通过减去两个Tick计数的差获得程序执行耗时。下面是示例代码:
// https://helloacm.com/the-rdtsc-performance-timer-written-in-c/
#include <iostream>
#include <cstdlib>
#include <stdint.h>
// Windows
#ifdef _WIN32
#include <intrin.h>
uint64_t rdtsc(){
return __rdtsc();
}
// Linux/GCC
#else
uint64_t rdtsc(){
unsigned int lo,hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return ((uint64_t)hi << 32) | lo;
}
#endif
using namespace std;
int main(int argc, char* argv[]) {
uint64_t tick = rdtsc(); // tick before
for (int i = 1; i < argc; ++ i) {
system(argv[i]); // start the command
}
cout << rdtsc() - tick << endl; // difference
return 0;
}
要编译它,请在源代码上命名,例如 rdtsc.cpp,然后运行以下命令:
g++ -o rdtsc rdtsc.cpp
编译完成后生成二进制文件:rdtsc
下面是如何使用rdtsp的示例:
Linux平台:
$ ./rdtsc 42 $ ./rdtsc "echo 1" 1 2257504 $ ./rdtsc "echo 1" "echo 2" 1 2 4705250 $ ./rdtsc "ls" rdtsc.cpp rdtsc 5441502
Windows平台:
$ rdtsc "echo a"
a
66071156
$ rdtsc "echo b" "echo c"
b
c
117783468
$ rdtsc "dir"
Volume in drive C is Windows
Volume Serial Number is XXX
Directory of C:\Dropbox\projects\rdtsc\Release
01/06/2017 17:03 DIR .
01/06/2017 17:03 DIR ..
01/06/2017 17:03 10,240 rdtsc.exe
01/06/2017 17:03 28,502 rdtsc.iobj
01/06/2017 17:03 4,832 rdtsc.ipdb
01/06/2017 17:03 585,728 rdtsc.pdb
4 File(s) 629,302 bytes
2 Dir(s) 195,310,538,752 bytes free
63903705
文章的脚注信息由WordPress的wp-posturl插件自动生成

微信扫一扫,打赏作者吧~![[整理][转载]win下网卡抓包发包库Npcap使用](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2023/08/demo_1-1024x711.jpg&w=280&h=210&zc=1)
![[转载]基础数据char,int,double,string是线程安全的吗?](http://www.jyguagua.com/wp-content/themes/begin/img/random/11.jpg)
![[整理]strcmp汇编写法](http://www.jyguagua.com/wp-content/themes/begin/img/random/8.jpg)
