One of my data structures and algorithms questions is to analyse assembly code and figure out the time complexity of it. I just don't understand the example my professor gave me.
It is to turn C code into assembly instructions using http://gcc.godbolt.org/
The C code is:
int main(void)
{
int a[] = {11,-22,33}, length = 3, count = 0;
for (int i = 0 ; i < length ; i++)
if (a[i] > 5)
count++;
}
The assembly code is:
main:
pushq %rbp
movq %rsp, %rbp
movl $11, -32(%rbp)
movl $-22, -28(%rbp)
movl $33, -24(%rbp)
movl $3, -12(%rbp)
movl $0, -4(%rbp)
movl $0, -8(%rbp)
.L4:
movl -8(%rbp), %eax
cmpl -12(%rbp), %eax
jge .L2
movl -8(%rbp), %eax
cltq
movl -32(%rbp,%rax,4), %eax
cmpl $5, %eax
jle .L3
addl $1, -4(%rbp)
.L3:
addl $1, -8(%rbp)
jmp .L4
.L2:
movl $0, %eax
popq %rbp
ret
And his explanation is:
Best case: Number of Instructions = 2 + n + 3 + 3(n+1) + 5n + 0 + 2n + 3 = 11n + 11
Worst case: Replace 0 by n to get Number of Instructions = 12n + 11
His rough explanation is:
Because we both approximate and also ignore actual constants (eg 11*t0), it is easier to reason as follows. The loop is executed n times, and the loop contents takes constant time, so total time is O(n). Most of the time we only use a rough analysis, which can be justified by the detailed analysis.
I do not understand the explanation. Can someone explain this to me better?