0

I was able to get it in seconds, but how to get the value of milliseconds? I am trying with the gettimeofday system call:

sys_gettimeofday_ms:
enter   $0, $0
pushq   $0
pushq   $2
leaq    -16(%rbp), %rdi
mov     $96, %rax
syscall

movq    -16(%rbp), %rax

leave
ret
Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82

1 Answers1

0

This might work (untested), targeting x86_64 Linux.

sys_gettimeofday_ms:
    mov rax, 96
    lea rdi, [rsp - 16]
    xor esi, esi
    syscall
    mov ecx, 1000
    mov rax, [rdi + 8]
    xor edx, edx
    div rcx
    mov rdx, [rdi]
    imul rdx, rcx
    add rax, rdx
    ret
E_net4
  • 27,810
  • 13
  • 101
  • 139
xiver77
  • 2,162
  • 1
  • 2
  • 12
  • I put your code into AT&T syntax, and it works! Thank you! What exactly are you doing? Why is that part necessary after the syscall? – Gergely Bertalan Mar 24 '22 at 12:24
  • `rdi` (or `rsp - 16`) stores `struct timeval {time_t tv_sec; suseconds_t tv_usec;};`. so multiply `1000` to `tv_sec` and divide `1000` to `tv_usec`, and add them together. – xiver77 Mar 24 '22 at 12:29
  • 1
    You should include high-level explanation like that in your answers in the first place, not just dump code. Also, gettimeofday is deprecated for clock_gettime; it's already implemented by converting nanosec to microsecs, so this is yet another layer of work. Also, you could use compiler output to get a much more efficient conversion that doesn't involve `div`. Or manually use 32-bit `div` since a normalized micro or nanoseconds fits in 32 bits. And `imul rdx, [rdi], 1000`. – Peter Cordes Mar 24 '22 at 18:48
  • Also, calling into the VDSO is much lower overhead than an actual `syscall`, especially in modern Linux with Spectre/Meltdown mitigation. The kernel exports code+data (scale factors) for pure user-space time functions, using scale factors for RDTSC. But then you'd have to look up syntax for how to get the linker to resolve a call to the VDSO. Glibc's gettimeofday and clock_gettime wrappers do that, so that might be a place to look. – Peter Cordes Mar 24 '22 at 18:49