简体   繁体   中英

How to get the exact number of times that a function is executed in C++?

#include<iostream>
using namespace std;

void callMe()
{
    int count=0;
    cout<<"I am called "<<++count<<" times!\n";
}

int main()
{
    callMe();
    callMe();
    callMe();
    callMe();
    return 0;
}

In this case, the output will be

I am called 1 times!
I am called 1 times!
I am called 1 times!
I am called 1 times!

Instead, I want the output printed as

I am called 1 times!
I am called 2 times!
I am called 3 times!
I am called 4 times!

I hope that the following code snippet will solve your issue!

#include<iostream.h>

void callMe()
{
    static int count=0;
    cout << "I am called " << ++count << " times!\n";
}

int main()
{
    callMe();
    callMe();
    callMe();
    callMe();
    return 0;
}

Here the static variable will retain its value and it will print the count incremented each time!

void callMe()
{
    static int count = 0; // note 'static' keyword
    cout<<"I am called "<<++count<<" times!\n";
}

make a static variable

so define it in function itself and due to property of static it will retain it's value in each call.

void callMe()
{
    static int count=0;
    cout<<"I am called "<<++count<<" times!\n";
}

static storage is done in data segement it's not on the function stack so in each call function will take it's modified value . So it will print your desired result.

but the count you have declared is local and have storage on stack so for each function call it always takes count = 0

3 ways actually, 2 of them have already been mentioned here. I would summarize along with reasons:

1) Declare the variable as Static:

void callMe()
{
    static int count=0;
    cout<<"I am called "<<++count<<" times!\n";
}

This works because the memory now creates a single copy of count, instead of creating one every time the function is called and then deleting it when the function is done. Also worth noticing here is that count is still Local to the function ie if you try to do something like this:

int main()
{
    int count;
    callMe();
    callMe();
    callMe();
    callMe();
    cout<<"you called "<<count<<"functions!\n";
    return 0;
}

count will still display a garbage value because the count for your function and count for your main are 2 different variables in 2 different locations.

2) Intialize a global variable:

int count=0; 
void callMe()
{
    cout<<"I am called "<<++count<<" times!\n";
}

In the above example, the variable has a scope that is global therefore the whole program uses a single copy of the variable, and hence the changes made somewhere will reflect everywhere in the program. You can use this approach if you need to monitor more than 2 functions. for eg:

int count=0;
void callMe()
{
    cout<<"I am called "<<++count<<" times!\n";
}

void callMe2()
{
    cout<<"I am called 2 "<<++count<<" times!\n";
}

int main()
{
    callMe();
    callMe();
    callMe2();
    callMe2();
    cout<<"you called "<<count<<" functions!\n";
    return 0;
}

Since count here is basically common to both the functions and the main, they all refer to the same value instead of making their own local copies. Could be messed up if you have variables with same name. To understand difference between global and static variable and their scope click here

3) Pass a reference of the variable:

void callMe(int &count)
{
   cout<<"I am called "<<count++<<" times!\n";
}

void callMe2(int &count)
{
   cout<<"I am called 2 "<<++count<<" times!\n";
}

int main()
{
    int count=0;
    callMe(count);
    callMe(count);
    callMe2(count);
    callMe2(count);
    cout<<"you called "<<count<<" functions!\n";
    return 0;
}

This is probably the cleanest way to do this, the variable is local to the main (which would save you garbage collection complications) and since this is a pass by refrence, all changes made point to the same location in the memory. If you don't have a solid reason not to follow this, I would say use this.

Hope I didn't confuse you further, Happy hunting.

You will have to pass it as an argument or store it as function state.

int count = 0;
auto callMe = [=] mutable {
    cout<<"I am called "<<++count<<" times!\n";
};

If you want to count the number of calls of a single function you could indeed use the static counter variable.


Alternatively, if you want to do this for debug purposes it's not the worst idea to use a profiling tool for this. For example Valgrind's Callgrind [emphasis mine]:

Callgrind is a profiling tool that records the call history among functions in a program's run as a call-graph. By default, the collected data consists of the number of instructions executed, their relationship to source lines, the caller/callee relationship between functions, and the numbers of such calls.


When you use gcc you could also tinker around with the __PRETTY_FUNCTION__ macro and a global map:

#include <iostream>
#include <string>
#include <map>

std::map<std::string, int> call_counts;

void call_me_one() {
    call_counts[__PRETTY_FUNCTION__] += 1;
}

void call_me_two() {
    call_counts[__PRETTY_FUNCTION__] += 1;
}

void call_me_three() {
    call_counts[__PRETTY_FUNCTION__] += 1;
}

int main()
{
    for (int i = 0; i < 10; i++) 
        call_me_one();

    for (int i = 0; i < 20; i++) 
        call_me_two();

    for (int i = 0; i < 30; i++) 
        call_me_three();

    for (auto it = call_counts.begin(); it != call_counts.end(); ++it)
        std::cout << (*it).first << " was being called " 
            << (*it).second << " times.\n";
}

Here's the output on my machine:

void call_me_one() was being called 10 times.
void call_me_three() was being called 30 times.
void call_me_two() was being called 20 times.

You have to use "static" keyword before count.

Rectified Code Snippet will be something like this: *

void callMe()
{
    static int count;
    cout<<"I am called "<<++count<<" times!\n";
}

You can pass the variable count by reference and increase it every time the function is called like this:

void callMe(int &count)
  {
     cout<<"I am called "<<count++<<" times!\n";
  }

int main()
  {
    int count=0;
  callMe(count);
  callMe(count);
  callMe(count);
  callMe(count);
  return 0;
  }

For more information about passing-by-reference you can refer here .

Essentially what everyone here suggests. This is a macro I've used from time to time. I find it makes for easier reading.

in a separate header: (say debug_helper.h)
---------------------
#define COUNT_USAGE() {static int count=0;++count;std::cout<<"Called "<<count<<" times\n";}

In the CPP file:
----------------
#include "debug_helper.h"    

void callMe()
{
    COUNT_USAGE();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM