Search code examples
cassemblyx86-64nasmdelay

How to implement usleep in x86_64 asm?


I've just started learning x86_64 asm and I would like to implement a usleep like procedure without using any syscalls.

extern void my_usleep(int);
my_usleep:
    ; stuff
    ret

Solution

  • I've just started learning x86_64 asm and I would like to implement a usleep like procedure without using any syscalls.

    Without using any system calls; the only viable option would be a busy loop relying on the timestamp from either the rdtsc or rdtscp instruction.

    This involves converting the delay from microseconds into whatever the CPU's TSC frequency is (which needs to be determined somehow, possibly by measuring it with some other time source), in addition to avoiding various pitfalls (e.g. time stamp being different on different CPUs); and these things make it "not easy".

    The other problem is that for a CPU running at several GHz each microsecond represents thousands of wasted clock cycles that the CPU could've spent doing useful work/running a different task, or even just doing nothing efficiently (by switching the CPU into a power saving state until a timer IRQ occurs). This is why a system call is better - the kernel is the only thing that has the privilege needed to implement time delays efficiently.