Skip to content

C++:Tip

Which loop has better performance

for (int i=0;i<=10;i++) {
    /* This is better? */
}
for (int i=10;i>=0;i--) {
    /* This is better? */
}

Incrementing and decrementing (INC and DEC, when translated into assembler commands) have the same speed of 1 CPU cycle.

However, the second can be theoretically faster on some (e.g. SPARC) architectures because no 10 has to be fetched from memory (or cache): most architectures have instructions that deal in an optimized fashion when compating with the special value 0 (usually having a special hardwired 0-register to use as operand, so no register has to be "wasted" to store the 10 for each iteration's comparison).

A smart compiler (especially if target instruction set is RISC) will itself detect this and (if your counter variable is not used in the loop) apply the second "decrement downto 0" form.

Please see answers https://stackoverflow.com/a/2823164/1018783 and https://stackoverflow.com/a/2823095/1018783 for further details.

Debugging Interrupt

아래와 같은 인라인 어셈블리 코드로 인터럽트를 넘기면 바로 디버깅이 가능하다.

__asm { int 3 };

Execute file path

OS별, 실행된 EXE파일의 경로를 확인하기 위한 방법은 아래와 같다:

  • Mac OS X: _NSGetExecutablePath() (man 3 dyld)
  • Linux: readlink /proc/self/exe
  • Solaris: getexecname()
  • FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
  • FreeBSD if it has procfs: readlink /proc/curproc/file (FreeBSD doesn't have procfs by default)
  • NetBSD: readlink /proc/curproc/exe
  • DragonFly BSD: readlink /proc/curproc/file
  • Windows: GetModuleFileName() with hModule = NULL

See also

Favorite site