tb044491
tb044491

Reputation: 144

rdtsc returns no results

i am attempting to use rdtsc for a timer, but both the eax and edx registers either remain empty or they form a number very different from the one given by the __rdtsc function from MS's instrin.h library.

here's the assembly code:

.model flat, c

.code

get_curr_cycle proc
cpuid
cpuid
cpuid
xor eax, eax ; empty eax register
xor edx, edx ; empty edx register
rdtsc
shl edx, 32 ; shift high bits to the left
or edx, eax ; or the high bits to the low bits
mov eax, edx ; move the final result into eax
retn
get_curr_cycle endp

end

and here is the c++ code:

#include <iostream>
#include <intrin.h>

extern "C" long long get_curr_cycle();

int main()
{
    long long t1 = __rdtsc();
    long long t2 = get_curr_cycle();

    for(unsigned int i = 0; i <= 10; ++i)
    {
        printf("%d - %d\n", t1, t2);
    }

    getchar();

    return 0;
}

here's my last output:

87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162
87592744 - 31162

Upvotes: 0

Views: 347

Answers (1)

catnip
catnip

Reputation: 25388

According to Wikipedia:

The instruction RDTSC returns the TSC in EDX:EAX. In x86-64 mode, RDTSC also clears the higher 32 bits of RAX and RDX.

So, on x86, your code can simply be:

get_curr_cycle proc
rdtsc
retn
get_curr_cycle endp

Which will return the current timer value in edx:eax.

On x64, you can do:

get_curr_cycle proc
rdtsc
shl rdx, 32
or rax, rdx
retn
get_curr_cycle endp

This will return the timer value in rax.

Also, your format specifiers for printf are wrong. They should be %lld.

Upvotes: 2

Related Questions