c++ - 如何报告 C++ 程序中的函数计算次数

标签 c++

我编写了一个 C++ 程序,用于计算最小化函数的算法的目标函数值。我想知道该算法使用了多少目标函数评估。还有许多其他函数调用目标值函数。

我这里有演示代码...

#include <iostream>    
#include <stdlib.h>    


using namespace std;

void prnt(){
    static int num = 0;
    cout << "Hello" << endl;
    num++;
    cout << num << endl;
}

void callprnt(){
    prnt();
}

int main() {

    for (int i = 0; i < 8; ++i)
    {
        prnt();
    }

    for (int i = 0; i < 10; ++i)
    {
        callprnt();
    }

}

如您所见,我可以在 prnt() 函数中显示正在发生多少目标函数评估,但我想在 main 中访问它。知道如何有效地跟踪主要功能评估的数量吗?

最佳答案

有几种方法可以解决这个问题。

一个不好的方法是使用全局变量。

更好的方法是返回计数,或传入一个变量(作为指针或引用)以进行跟踪。

或者,您可以在类里面跟进。

using namespace std;

class Printer
{
public:
    Printer() : num(0) {}
    void prnt() {
        cout << "Hello" << endl;
        num++;
        cout << num << endl;
    }
    int count()
    {
        return num;
    }
private:
    int num;
};

void callprnt(Printer & p) {
    p.prnt();
}

int main() {
    Printer p;
    for (int i = 0; i < 8; ++i)
    {
        p.prnt();
    }

    for (int i = 0; i < 10; ++i)
    {
        callprnt(p);
    }

    cout << "Total count: " << p.count() << '\n';
}

一般来说,你可以让 Printer 实际上是一个计数器,然后传入你需要调用的函数。

关于c++ - 如何报告 C++ 程序中的函数计算次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41614497/

相关文章:

c++ - 为什么做赋值不会使对象指向同一位置

c++ - c++:struct和decltype比较器的priority_queue

c# - 从 C++ 反序列化 protobuf 并在 C# 中重新序列化给出不同的输出

C++ 最终类和切片习惯用法

c# - 如何识别某个值是否在 C++ 的枚举类型中定义?

c++ - 从 C++ 调用 matlab

c++ - 浮点比较的不可再现性

c++ - 在继承类中删除会导致符号查找错误

c++ - shared_ptr 空指针和赋值

c++ - 在没有其他库的情况下用纯 c/c++ 编写 BMP 图像