Search code examples
performanceruntimepseudocodeoperation

How to count the number of operations including an 'if... else...' statement?


Say I was calculating the running time of the following pseudocode using operation counting:

if(a > b) then    [1 operation]
    return a-b    [1 operation]
else
    return b-a    [1 operation]

Would I count the total number of operation including both of the return statements (3 operations)? Or, since we normally look at the worst case scenario when calculating the running time - would I not count the first return statement as an operation since it would not be executed in the worst case scenario(2 operations)?


Solution

  • When profiling code, you have to take branching conditions into account such as loops and if-statements. Each branch of code ends in a return statement.

    So in your code, you make two branches once you hit the if. Both branches have the same number of operations, though, a single subtraction.

    Basically, the worst case is the longest path of code to a single return statement.