mschrimpf
mschrimpf

Reputation: 559

sleep without system or IO calls

I need a sleep that does not issue any system or IO calls for a scenario with Hardware Transactional Memory (these calls would lead to an abort). Sleeping for 1 microsecond as in usleep(1) would be just fine.

This question suggests to implement nested loops to keep the program busy and delay it for some time. However, I want to be able to compile with optimization which would delete these loops.

An idea could be to calculate some sophisticated math equation. Are there approaches to this? The actual time waited does not have to be precise - it should be vaguely the same for multiple runs however.

Upvotes: 0

Views: 606

Answers (3)

Matthew G.
Matthew G.

Reputation: 1350

Try a nop loop with a volatile asm directive:

for (int i = 0; i < 1000; i++) { 
    asm volatile ("nop"); 
} 

The volatile should prevent the optimizer from getting rid of it. If that doesn't do it, then try __volatile__.

Upvotes: 2

HolyBlackCat
HolyBlackCat

Reputation: 96246

You can use this code:

#include <time.h>

void delay(int n)
{
    n *= CLOCKS_PER_SEC / 1000;
    clock_t t1 = clock();
    while (clock() <= t1 + n && clock() >= t1);
}

Sometimes (not very often) this function will cause less delay than specified due to clock counter overflow.

Update

Another option is to use a loops like this with volatile counters.

Upvotes: 0

Sebastian Redl
Sebastian Redl

Reputation: 71989

The tricky part here is the timing. Querying any sort of timer may well count as an I/O function, depending on the OS.

But if you just want a delay loop, when timing isn't that important, you should look to platform-specific code. For example, there is an Intel-specific intrinsic called _mm_pause that translates to a CPU pause instruction, which basically halts the pipeline until the next memory bus sync comes through. It was designed to be put into a spinlock loop (no point in spinning and requerying an atomic variable until there is a possibility of new information), but it might (might - read the documentation) inhibit the compiler from removing your delay loop as empty.

Upvotes: 0

Related Questions