如何计算包含“if...else..."语句的操作次数? [英] How to count the number of operations including an 'if... else...' statement?

查看:65
本文介绍了如何计算包含“if...else..."语句的操作次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用操作计数计算以下伪代码的运行时间:

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]

我会计算包括两个返回语句(3 个操作)在内的操作总数吗?或者,由于我们在计算运行时间时通常会考虑最坏的情况 - 我会不会将第一个 return 语句视为一个操作,因为它不会在最坏的情况下执行(2 个操作)?

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)?

推荐答案

在分析代码时,您必须考虑分支条件,例如循环和 if 语句.每个代码分支都以 return 语句结束.

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.

因此,在您的代码中,一旦点击 if,您就会创建两个分支.但是,两个分支的运算次数相同,只是一次减法.

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.

这篇关于如何计算包含“if...else..."语句的操作次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆