ROOT lags when creating large multi-dimensional vector of TH1 pointers

Hi all,

I am trying to create a large multi-dimensional vector of TH1D pointers. I’d like to be able to declare each histogram with a name, title, and bin specifications (as the example shows below). However, I have noticed that this significantly slows down the code. If I instead use the default construction TH1D* histo = new TH1D(), I don’t experience any delays. This is a problem, however, because I need to be able to specify bin start/end/widths.

Is there a way to get around this issue? I realize there is a very large number of histograms being generated here. Is that part of the problem itself?

   // ratios[c][x][i][r] = TH1D
   std::vector<std::vector<std::vector<std::vector<TH1D*>>>> ratios;
   ratios.resize(24);

   for (int c=0;c<24;c++){
      ratios[c].resize(54);
      for (int x=0;x<54;x++){
        ratios[c][x].resize(4);
        for (int i=0;i<4;i++){
           ratios[c][x][i].resize(0);
           for (int r=0;r<=80;r++){
              TH1D* histo = new TH1D(
                                      Form("c%i xt%i p%i r%i ",c,x,i,r),
                                      Form("c%i x% i p%i r%i ",c,x,i,r),
                                                      100, 0, 20);
              ratios[c][x][i].push_back(histo);
           }
        }
      }
    }

Please read tips for efficient and successful posting and posting code

ROOT Version: 6.12
Platform: Not Provided
Compiler: Not Provided


Hi @zepyoorkhechadoorian ,
and welcome to the ROOT forum!
Named histograms are registered with ROOT’s memory management system. That’s probably what’s taking time when you create many of them in a hot loop (it would be good to verify what methods take time exactly e.g. with perf on Linux).

You can try calling the static method TH1::AddDirectory(false) before the outer for loop to deactivate this behavior to see if it improves runtimes.

Cheers,
Enrico

P.S.
unrelated, but ROOT v6.12 is very old, newer versions contain many bug fixes and performance improvements that might be generally helpful

1 Like

Thank you so much for the tip. This fixed my problem very smoothly!

1 Like