[英]How long it takes to GCC compiler execute an asm volatile (“nop”/::) instruction?
I have a C code in UNIX where I need to keep my processor doing nothing for 2 seconds. 我在UNIX中有一个C代码,我需要保持处理器2秒钟不执行任何操作。 In order to do that, I found the assembly instruction asm volatile("nop"::) . 为此,我找到了汇编指令asm volatile(“ nop”::) 。 I've searched a lot but I couldn't find anywhere explaining how can I calculate the necessary number of NOPs to execute my function for exactly 2 seconds. 我进行了很多搜索,但找不到任何地方可以解释如何计算2秒钟内执行我的功能所需的NOP数。 Can anyone help me? 谁能帮我?
for(i = 0; i < COUNTER; i++){
asm volatile ("nop"::);
}
The NOP instruction takes one cycle in most microprocessors, so do the math: 在大多数微处理器中,NOP指令占用一个周期,因此数学公式也是如此:
eg, on a 8 MHz processor, one cycle takes 1 / 8 MHz = 125 ns. 例如,在8 MHz处理器上,一个周期占用1/8 MHz = 125 ns。 You then have to add few cycles more for the management of the loop. 然后,您必须再增加几个循环来管理循环。
If you are in an environment with an OS you should not rely on NOP instructions to wait for seconds and should not use an active wait. 如果您所在的操作系统是OS,则不应依靠NOP指令等待几秒钟,也不应使用主动等待。 On POSIX systems (like UNIX), use POSIX nanosleep functions. 在POSIX系统(如UNIX)上,使用POSIX nanosleep函数。
只需包含unistd.h并使用:
unsigned int sleep(unsigned int seconds);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.