c++ - 如何进行时间分析

标签 c++ time analysis

我必须为使用循环计算从1到n的所有整数之和的函数编写代码。
我还需要进行时间分析,将每个基本操作(例如赋值和++)计为一个操作。我需要了解如何计算每个基本操作的帮助。 int computeSume(int n)是C1的第一步吗? for循环是多个步骤吗?
请帮忙解释。谢谢。

#include <iostream>

using namespace std;

//Create a function that uses a loop to compute the sum of all integers from 1 to n.

//Create Function
int computeSum(int n)
{
    //create sum variable
    int sum = 0;
    
    //create for loop
    // i must be <= to n so it will count all integers and not cut the last int off.
    for (int i = 0; i <= n; i++)
    {
        sum = sum + i;
    }
        //return statement
        return sum;
}

//Main Method
int main()
{
    //Input varibale
    int n;
    
    //Create user prompt
    cout << "Enter a value: " << endl;
    cin >> n;
    cout << "The sum of all integer from 1 to " << n << " is " << computeSum(n) << "." << endl;
    
    return 0;
}

最佳答案

看看这种和平,我注释掉了必要的信息供您引用。

#include <iostream>

using namespace std;

int computeSum(int n)
{
    int sum = 0;        // One unit time.
    
    
    for (int i = 0; i <= n; i++)        // Condition will be checked N+1 times so n+1 unit time.
    {
        sum = sum + i;
    }
        
    return sum;     // One unit time.

    // Total units of time is N+3, which is nothing but O(N).
}

//Main Method
int main()
{
    
    int n;          // Declaring a variable is one unit time.
    
    cout << "Enter a value: " << endl;      // One unit time.
    cin >> n;           // Depends how much time you take to enter value, But for simplicity taking as 1 unit.
    cout << "The sum of all integer from 1 to " << n << " is " << computeSum(n) << "." << endl;     // It could have been taken only a simple statement with one unit time.
                                                                                                    // But computeSum(n) is a function so, we first analyse it's time.
    
    return 0;       // one unit.
}

关于c++ - 如何进行时间分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63527602/

相关文章:

c++ - 带有 float 的奇怪的谷歌测试失败

c++ - 如何查明长函数返回的位置

javascript - 在 Node.js 中向 javascript 日期添加分钟

c# - 用C#制作一个简单的数据库程序

c++ - 我需要帮助编写一个为两个函数接受两个参数的 C++ 程序吗?

c++ - 将成员函数指针传递给 c 风格的函数

c++ - OpenCV - BFMatcher 只检查对象特征之间的距离,而不检查场景特征之间的距离?

Python:将自由文本转换为日期

time - 着色器时间统一 -clock_gettime 被截断

Python,使用difflib逐字比较两个句子