What is the correct way to save a histogram which takes a lot of data from Many input files?

Have you run the “MakeClass” on the TChain (mandatory in your case) or on a single TTree (will create a misbehaving class in your case)?

In order to do it correctly for a TChain, in an interactive ROOT session, try something like this:

TChain *t = new TChain("TTreeName");
t->AddFile("SomeFileName.root"); // (at least) one file (is sufficient)
t->LoadTree(0); // just the very first entry
t->MakeClass("NewClassName");
delete t; // cleanup

In principle, the “NewClassName::Loop()” method could look like this:

void NewClassName::Loop()
{
  if (fChain == 0) return; // just a precaution

  TFile *fout = TFile::Open("output_file.root", "recreate");
  if (fout) fout->cd(); // all new histograms will be connected to "fout"
  // ... create / book / initialize all histograms here ...

  Long64_t nentries = fChain->GetEntriesFast();

  Long64_t nbytes = 0, nb = 0;
  for (Long64_t jentry = 0; jentry < nentries; jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry); nbytes += nb;
    // if (Cut(ientry) < 0) continue;
    // ... fill all histograms with the current "jentry" data here ...
  }

  if (fout) fout->Write(); // save all histograms
  delete fout; // automatically deletes all histograms, too
  fout = 0; // just a precaution
}

See also:

1 Like