C++ something wrong with this code?
I'm trying to get a way to find some sort of nanos开发者_如何学Pythonecond-level timing for an encryption method. I found this code on stackoverflow and it doesnt appear to compile in VS2010 but i cant figure out why. The error is with 'time = GetCpuClocks()' and says "error C3861: 'GetCpuClocks': identifier not found", i dont quite understand why? I was also having a problem with the 'int32' type in the struct declaration.
(I presume declaring 'time' as 'long' is ok? Or should it have been __int64 ?
Thanks in advance
int _tmain(int argc, _TCHAR* argv[])
{
__int64 time;
time = GetCpuClocks();
}
inline __int64 GetCpuClocks() {
// Counter
struct { int32 low, high; } counter;
// Use RDTSC instruction to get clocks count
__asm push EAX
__asm push EDX
__asm __emit 0fh
__asm __emit 031h
// RDTSC
__asm mov counter.low, EAX
__asm mov counter.high, EDX
__asm pop EDX
__asm pop EAX
// Return result
return *(__int64 *)(&counter);
}
put a signature ABOVE your main
__int64 GetCpuClocks();
You need to add two undersocres to the datatype: __int32
The reason you need to use 32-bit integers is because the ASM commands are using the 32-bit registers, and therefore 32-bit integers are much faster to copy than a single 64-bit integer. The cast in the return statement combines the two 32-bit integers into the final 64-bit result with little or no extra time spent.
The reason to use __int32 and __int64 instead of int and long is because __int32/64 have universally set sizes, whereas short, int, and long technically have variable sizes depending on the compiler and the platform architecture.
(Of course, you already know about the fact that the functions need to be declared in reverse order.)
The code refers to GetCpuClocks() in line 4, but GetCpuClocks is undefined until line 7.
Change the order of function definitions. GetCpuClocks should be defined or forward declared before the call in main.
精彩评论