Epoch in Assembly Language
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Assembly Language.
section .data
fmt_time db "Current time: %s", 10, 0
fmt_seconds db "Seconds since epoch: %lld", 10, 0
fmt_milliseconds db "Milliseconds since epoch: %lld", 10, 0
fmt_nanoseconds db "Nanoseconds since epoch: %lld", 10, 0
section .bss
time_buf resb 64
section .text
global main
extern printf
extern time
extern ctime
main:
push rbp
mov rbp, rsp
; Get current time
xor rdi, rdi
call time
mov rdi, rax
; Print current time
call ctime
mov rsi, rax
mov rdi, fmt_time
xor eax, eax
call printf
; Print seconds since epoch
xor rdi, rdi
call time
mov rsi, rax
mov rdi, fmt_seconds
xor eax, eax
call printf
; Print milliseconds since epoch (approximation)
xor rdi, rdi
call time
imul rax, 1000
mov rsi, rax
mov rdi, fmt_milliseconds
xor eax, eax
call printf
; Print nanoseconds since epoch (approximation)
xor rdi, rdi
call time
imul rax, 1000000000
mov rsi, rax
mov rdi, fmt_nanoseconds
xor eax, eax
call printf
mov rsp, rbp
pop rbp
xor eax, eax
ret
This Assembly Language code demonstrates how to get the current time and calculate the number of seconds, milliseconds, and nanoseconds since the Unix epoch.
We use the time
function to get the current time in seconds since the epoch. The ctime
function is used to convert the time value to a human-readable string.
To print the values, we use the printf
function. Note that in Assembly, we don’t have direct equivalents for milliseconds and nanoseconds since the epoch, so we approximate them by multiplying the seconds value.
To compile and run this program (assuming you’re using NASM and gcc on a Unix-like system):
$ nasm -f elf64 epoch.asm
$ gcc -no-pie epoch.o -o epoch
$ ./epoch
Current time: Wed Jun 14 12:34:56 2023
Seconds since epoch: 1686745496
Milliseconds since epoch: 1686745496000
Nanoseconds since epoch: 1686745496000000000
Note that the actual output will vary depending on when you run the program.
Assembly Language doesn’t have built-in functions for precise millisecond or nanosecond timing, so these values are approximations based on the second count. For more precise timing in real-world applications, you would typically use system-specific APIs or hardware timers.