Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
hist103_THnSparse_hist.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_hist
3/// Evaluate the performance of THnSparse vs TH1/2/3/nF
4/// for different numbers of dimensions and bins per dimension.
5///
6/// The script calculates the bandwidth for filling and retrieving
7/// bin contents (in million entries per second) for these two
8/// histogramming techniques, where "seconds" is CPU and real time.
9///
10/// The first line of the plots contains the bandwidth based on the
11/// CPU time (THnSpase, TH1/2/3/nF*, ratio), the second line shows
12/// the plots for real time, and the third line shows the fraction of
13/// filled bins and memory used by THnSparse vs. TH1/2/3/nF.
14///
15/// The timing depends on the distribution and the amount of entries
16/// in the histograms; here, a Gaussian distribution (center is
17/// contained in the histograms) is used to fill each histogram with
18/// 1000 entries. The filling and reading is repeated until enough
19/// statistics have been collected.
20///
21/// tutorials/io/tree/tree143_drawsparse.C shows an example for visualizing a
22/// THnSparse. It creates a TTree which is then drawn using
23/// TParallelCoord.
24///
25/// This macro should be run in compiled mode due to the many nested
26/// loops that force CLING to disable its optimization. If run
27/// interpreted one would not benchmark THnSparse but CLING.
28///
29/// Run as:
30/// ~~~{.cpp}
31/// root[0] .L $ROOTSYS/tutorials/hist/hist103_THnSparse_hist.C+
32/// root[1] hist103_THnSparse_hist()
33/// ~~~
34///
35/// \macro_code
36///
37/// \date October 2023
38/// \author Axel.Naumann
39
40#include "TH1.h"
41#include "TH2.h"
42#include "TH3.h"
43#include "THn.h"
44#include "THnSparse.h"
45#include "TStopwatch.h"
46#include "TRandom.h"
47#include "TCanvas.h"
48#include "TFile.h"
49#include "TStyle.h"
50#include "TSystem.h"
51
52#include <limits>
53
54class TTimeHists {
55public:
56 enum EHist {
57 kHist,
58 kSparse,
59 kNumHist
60 };
61 enum ETime {
62 kReal,
63 kCPU,
64 kNumTime
65 };
66 TTimeHists(Int_t dim, Int_t bins, Long_t num)
67 : fValue(nullptr), fDim(dim), fBins(bins), fNum(num), fSparse(nullptr), fHist(nullptr), fHn(nullptr)
68 {
69 }
70 ~TTimeHists();
71 bool Run();
72 Double_t GetTime(EHist hist, ETime time) const
73 {
74 if (time == kReal)
75 return fTime[hist][0];
76 return fTime[hist][1];
77 }
78 static void SetDebug(Int_t lvl) { fgDebug = lvl; }
79 THnSparse *GetSparse() const { return fSparse; }
80
81protected:
82 void Fill(EHist hist);
83 Double_t Check(EHist hist);
84 void SetupHist(EHist hist);
85 void NextValues();
86 void SetupValues();
87
88private:
89 Double_t *fValue;
90 Int_t fDim;
91 Int_t fBins;
92 Long_t fNum;
93 Double_t fTime[2][2];
94 THnSparse *fSparse;
95 TH1 *fHist;
96 THn *fHn;
97 static Int_t fgDebug;
98};
99
100Int_t TTimeHists::fgDebug = 0;
101
102TTimeHists::~TTimeHists()
103{
104 delete[] fValue;
105 delete fSparse;
106 delete fHist;
107 delete fHn;
108}
109
110bool TTimeHists::Run()
111{
112 // run all tests with current settings, and check for identity of content.
113
114 Double_t check[2];
115 Long64_t rep[2];
116 for (int h = 0; h < 2; ++h) {
117 rep[h] = 0;
118 SetupValues();
119 try {
121 w.Start();
122 SetupHist((EHist)h);
123 w.Stop();
124 do {
125 w.Start(kFALSE);
126 Fill((EHist)h);
127 check[h] = Check((EHist)h);
128 w.Stop();
129 ++rep[h];
130 } while ((!h && w.RealTime() < 0.1) || (h && rep[0] > 0 && rep[1] < rep[0]));
131
132 fTime[h][0] = (1. * fNum * rep[h]) / w.RealTime() / 1E6;
133 fTime[h][1] = (1. * fNum * rep[h]) / w.CpuTime() / 1E6;
134
135 if (h == 1 && (fTime[h][0] > 1E20 || fTime[h][1] > 1E20)) {
136 do {
137 // some more cycles:
138 w.Start(kFALSE);
139 Fill((EHist)h);
140 Check((EHist)h);
141 w.Stop();
142 ++rep[h];
143 } while (w.RealTime() < 0.1);
144
145 fTime[h][0] = (1. * fNum * rep[h]) / w.RealTime() / 1E6;
146 fTime[h][1] = (1. * fNum * rep[h]) / w.CpuTime() / 1E6;
147 }
148
149 if (fTime[h][0] > 1E20)
150 fTime[h][0] = 1E20;
151 if (fTime[h][1] > 1E20)
152 fTime[h][1] = 1E20;
153 } catch (std::exception &) {
154 fTime[h][0] = fTime[h][1] = -1.;
155 check[h] = -1.; // can never be < 1 without exception
156 rep[h] = -1;
157 }
158 }
159 if (check[0] != check[1])
160 if (check[0] != -1.)
161 printf("ERROR: mismatch of histogram (%g) and sparse histogram (%g) for dim=%d, bins=%d!\n", check[0],
162 check[1], fDim, fBins);
163 // else
164 // printf("ERROR: cannot allocate histogram for dim=%d, bins=%d - out of memory!\n",
165 // fDim, fBins);
166 return (check[0] == check[1]);
167}
168
169void TTimeHists::NextValues()
170{
171 for (Int_t d = 0; d < fDim; ++d)
172 fValue[d] = gRandom->Gaus() / 4.;
173}
174
175void TTimeHists::SetupValues()
176{
177 // define fValue
178 if (!fValue)
179 fValue = new Double_t[fDim];
180 gRandom->SetSeed(42);
181}
182
183void TTimeHists::Fill(EHist hist)
184{
185 for (Long_t n = 0; n < fNum; ++n) {
186 NextValues();
187 if (fgDebug > 1) {
188 printf("%ld: fill %s", n, hist == kHist ? (fDim < 4 ? "hist" : "arr") : "sparse");
189 for (Int_t d = 0; d < fDim; ++d)
190 printf("[%g]", fValue[d]);
191 printf("\n");
192 }
193 if (hist == kHist) {
194 switch (fDim) {
195 case 1: fHist->Fill(fValue[0]); break;
196 case 2: ((TH2F *)fHist)->Fill(fValue[0], fValue[1]); break;
197 case 3: ((TH3F *)fHist)->Fill(fValue[0], fValue[1], fValue[2]); break;
198 default: fHn->Fill(fValue); break;
199 }
200 } else {
201 fSparse->Fill(fValue);
202 }
203 }
204}
205
206void TTimeHists::SetupHist(EHist hist)
207{
208 if (hist == kHist) {
209 switch (fDim) {
210 case 1: fHist = new TH1F("h1", "h1", fBins, -1., 1.); break;
211 case 2: fHist = new TH2F("h2", "h2", fBins, -1., 1., fBins, -1., 1.); break;
212 case 3: fHist = new TH3F("h3", "h3", fBins, -1., 1., fBins, -1., 1., fBins, -1., 1.); break;
213 default: {
214 MemInfo_t meminfo;
215 gSystem->GetMemInfo(&meminfo);
216 Int_t size = 1;
217 for (Int_t d = 0; d < fDim; ++d) {
218 if ((Int_t)(size * sizeof(Float_t)) > std::numeric_limits<int>::max() / (fBins + 2) ||
219 (meminfo.fMemFree > 0 && meminfo.fMemFree / 2 < (Int_t)(size * sizeof(Float_t) / 1000 / 1000)))
220 throw std::bad_alloc();
221 size *= (fBins + 2);
222 }
223 if (meminfo.fMemFree > 0 && meminfo.fMemFree / 2 < (Int_t)(size * sizeof(Float_t) / 1000 / 1000))
224 throw std::bad_alloc();
225 Int_t *bins = new Int_t[fDim];
226 Double_t *xmin = new Double_t[fDim];
227 Double_t *xmax = new Double_t[fDim];
228 for (Int_t d = 0; d < fDim; ++d) {
229 bins[d] = fBins;
230 xmin[d] = -1.;
231 xmax[d] = 1.;
232 }
233 fHn = new THnF("hn", "hn", fDim, bins, xmin, xmax);
234 }
235 }
236 } else {
237 Int_t *bins = new Int_t[fDim];
238 Double_t *xmin = new Double_t[fDim];
239 Double_t *xmax = new Double_t[fDim];
240 for (Int_t d = 0; d < fDim; ++d) {
241 bins[d] = fBins;
242 xmin[d] = -1.;
243 xmax[d] = 1.;
244 }
245 fSparse = new THnSparseF("hs", "hs", fDim, bins, xmin, xmax);
246 }
247}
248
249Double_t TTimeHists::Check(EHist hist)
250{
251 // Check bin content of all bins
252 Double_t check = 0.;
253 Int_t *x = new Int_t[fDim];
254 memset(x, 0, sizeof(Int_t) * fDim);
255
256 if (hist == kHist) {
257 Long_t idx = 0;
258 Long_t size = 1;
259 for (Int_t d = 0; d < fDim; ++d)
260 size *= (fBins + 2);
261 while (x[0] <= fBins + 1) {
262 Double_t v = -1.;
263 if (fDim < 4) {
264 Long_t histidx = x[0];
265 if (fDim == 2)
266 histidx = fHist->GetBin(x[0], x[1]);
267 else if (fDim == 3)
268 histidx = fHist->GetBin(x[0], x[1], x[2]);
269 v = fHist->GetBinContent(histidx);
270 } else
271 v = fHn->GetBinContent(x);
272 Double_t checkx = 0.;
273 if (v)
274 for (Int_t d = 0; d < fDim; ++d)
275 checkx += x[d];
276 check += checkx * v;
277
278 if (fgDebug > 2 || (fgDebug > 1 && v)) {
279 printf("%s%d", fDim < 4 ? "hist" : "arr", fDim);
280 for (Int_t d = 0; d < fDim; ++d)
281 printf("[%d]", x[d]);
282 printf(" = %g\n", v);
283 }
284
285 ++x[fDim - 1];
286 // Adjust the bin idx
287 // no wrapping for dim 0 - it's what we break on!
288 for (Int_t d = fDim - 1; d > 0; --d) {
289 if (x[d] > fBins + 1) {
290 x[d] = 0;
291 ++x[d - 1];
292 }
293 }
294 ++idx;
295 } // while next bin
296 } else {
297 for (Long64_t i = 0; i < fSparse->GetNbins(); ++i) {
298 Double_t v = fSparse->GetBinContent(i, x);
299 Double_t checkx = 0.;
300 for (Int_t d = 0; d < fDim; ++d)
301 checkx += x[d];
302 check += checkx * v;
303
304 if (fgDebug > 1) {
305 printf("sparse%d", fDim);
306 for (Int_t d = 0; d < fDim; ++d)
307 printf("[%d]", x[d]);
308 printf(" = %g\n", v);
309 }
310 }
311 }
312 check /= fNum;
313 if (fgDebug > 0)
314 printf("check %s%d = %g\n", hist == kHist ? (fDim < 4 ? "hist" : "arr") : "sparse", fDim, check);
315 return check;
316}
317
318void hist103_THnSparse_hist()
319{
320// Exclude this macro also for Cling as this script requires exception support
321// which is not supported in Cling as of v6.00/00.
322#if defined(__CLING__)
323 printf("Please run this script in compiled mode by running \".x hist103_THnSparse_hist.C+\"\n");
324 return;
325#endif
326
327 TH2F *htime[TTimeHists::kNumHist][TTimeHists::kNumTime];
328 for (int h = 0; h < TTimeHists::kNumHist; ++h)
329 for (int t = 0; t < TTimeHists::kNumTime; ++t) {
330 TString name("htime_");
331 if (h == 0)
332 name += "arr";
333 else
334 name += "sp";
335 if (t == 0)
336 name += "_r";
337
338 TString title;
339 title.Form("Throughput (fill,get) %s (%s, 1M entries/sec);dim;bins;1M entries/sec",
340 h == 0 ? "TH1/2/3/nF" : "THnSparseF", t == 0 ? "real" : "CPU");
341 htime[h][t] = new TH2F(name, title, 6, 0.5, 6.5, 10, 5, 105);
342 }
343
344 TH2F *hsparse_mem =
345 new TH2F("hsparse_mem", "Fractional memory usage;dim;bins;fraction of memory used", 6, 0.5, 6.5, 10, 5, 105);
346 TH2F *hsparse_bins = new TH2F("hsparse_bins", "Fractional number of used bins;dim;bins;fraction of filled bins", 6,
347 0.5, 6.5, 10, 5, 105);
348
349 // TTimeHists::SetDebug(2);
350 Double_t max = -1.;
351 for (Int_t dim = 1; dim < 7; ++dim) {
352 printf("Processing dimension %d", dim);
353 for (Int_t bins = 10; bins <= 100; bins += 10) {
354 TTimeHists timer(dim, bins, /*num*/ 1000);
355 timer.Run();
356 for (int h = 0; h < TTimeHists::kNumHist; ++h) {
357 for (int t = 0; t < TTimeHists::kNumTime; ++t) {
358 Double_t time = timer.GetTime((TTimeHists::EHist)h, (TTimeHists::ETime)t);
359 if (time >= 0.)
360 htime[h][t]->Fill(dim, bins, time);
361 }
362 }
363 hsparse_mem->Fill(dim, bins, timer.GetSparse()->GetSparseFractionMem());
364 hsparse_bins->Fill(dim, bins, timer.GetSparse()->GetSparseFractionBins());
365
366 if (max < timer.GetTime(TTimeHists::kSparse, TTimeHists::kReal))
367 max = timer.GetTime(TTimeHists::kSparse, TTimeHists::kReal);
368 printf(".");
369 fflush(stdout);
370 }
371 printf(" done\n");
372 }
373
374 Double_t markersize = 2.5;
375 hsparse_mem->SetMarkerSize(markersize);
376 hsparse_bins->SetMarkerSize(markersize);
377
378 TH2F *htime_ratio[TTimeHists::kNumTime];
379 for (int t = 0; t < TTimeHists::kNumTime; ++t) {
380 const char *name = t ? "htime_ratio" : "htime_ratio_r";
381 htime_ratio[t] = (TH2F *)htime[TTimeHists::kSparse][t]->Clone(name);
382 TString title;
383 title.Form("Relative speed improvement (%s, 1M entries/sec): sparse/hist;dim;bins;#Delta 1M entries/sec",
384 t == 0 ? "real" : "CPU");
385 htime_ratio[t]->SetTitle(title);
386 htime_ratio[t]->Divide(htime[TTimeHists::kHist][t]);
387 htime_ratio[t]->SetMinimum(0.1);
388 htime_ratio[t]->SetMarkerSize(markersize);
389 }
390
391 TFile *f = new TFile("sparsehist.root", "RECREATE");
392
393 TCanvas *canv = new TCanvas("c", "c");
394 canv->Divide(3, 3);
395
396 gStyle->SetPalette(8, nullptr);
398 gStyle->SetOptStat(0);
399 const char *opt = "TEXT COL";
400
401 for (int t = 0; t < TTimeHists::kNumTime; ++t) {
402 for (int h = 0; h < TTimeHists::kNumHist; ++h) {
403 htime[h][t]->SetMaximum(max);
404 htime[h][t]->SetMarkerSize(markersize);
405 canv->cd(1 + h + 3 * t);
406 htime[h][t]->Draw(opt);
407 htime[h][t]->Write();
408 }
409 canv->cd(3 + t * 3);
410 htime_ratio[t]->Draw(opt);
411 gPad->SetLogz();
412 htime_ratio[t]->Write();
413 }
414
415 canv->cd(7);
416 hsparse_mem->Draw(opt);
417 canv->cd(8);
418 hsparse_bins->Draw(opt);
419 hsparse_mem->Write();
420 hsparse_bins->Write();
421
422 canv->Write();
423
424 delete f;
425}
#define d(i)
Definition RSha256.hxx:102
#define f(i)
Definition RSha256.hxx:104
#define h(i)
Definition RSha256.hxx:106
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:69
float Float_t
Float 4 bytes (float)
Definition RtypesCore.h:72
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
double Double_t
Double 8 bytes.
Definition RtypesCore.h:74
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:84
char name[80]
Definition TGX11.cxx:142
float xmin
float xmax
THnSparseT< TArrayF > THnSparseF
Definition THnSparse.h:194
THnT< Float_t > THnF
Definition THn.h:224
R__EXTERN TRandom * gRandom
Definition TRandom.h:73
R__EXTERN TStyle * gStyle
Definition TStyle.h:442
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
#define gPad
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
The Canvas class.
Definition TCanvas.h:23
TVirtualPad * cd(Int_t subpadnumber=0) override
Set current canvas & pad.
Definition TCanvas.cxx:733
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:908
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:126
void SetTitle(const char *title) override
Change/set the title.
Definition TH1.cxx:6932
virtual void SetMaximum(Double_t maximum=-1111)
Definition TH1.h:682
void Draw(Option_t *option="") override
Draw this histogram with options.
Definition TH1.cxx:3193
virtual void SetMinimum(Double_t minimum=-1111)
Definition TH1.h:683
virtual Bool_t Divide(TF1 *f1, Double_t c1=1)
Performs the operation: this = this/(c1*f1) if errors are defined (see TH1::Sumw2),...
Definition TH1.cxx:2969
2-D histogram with a float per channel (see TH1 documentation)
Definition TH2.h:345
Int_t Fill(Double_t) override
Invalid Fill method.
Definition TH2.cxx:369
3-D histogram with a float per channel (see TH1 documentation)
Definition TH3.h:369
Efficient multidimensional histogram.
Definition THnSparse.h:37
Multidimensional histogram.
Definition THn.h:30
virtual Int_t Write(const char *name=nullptr, Int_t option=0, Int_t bufsize=0)
Write this object to the current directory.
Definition TObject.cxx:987
void Divide(Int_t nx=1, Int_t ny=1, Float_t xmargin=0.01, Float_t ymargin=0.01, Int_t color=0) override
Automatic pad generation by division.
Definition TPad.cxx:1362
virtual Double_t Gaus(Double_t mean=0, Double_t sigma=1)
Samples a random number from the standard Normal (Gaussian) Distribution with the given mean and sigm...
Definition TRandom.cxx:274
virtual void SetSeed(ULong_t seed=0)
Set the random generator seed.
Definition TRandom.cxx:614
Stopwatch class.
Definition TStopwatch.h:28
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
Basic string class.
Definition TString.h:137
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2438
void SetOptStat(Int_t stat=1)
The type of information printed in the histogram statistics box can be selected via the parameter mod...
Definition TStyle.cxx:1641
void SetPaintTextFormat(const char *format="g")
Definition TStyle.h:390
void SetPalette(Int_t ncolors=kBird, Int_t *colors=nullptr, Float_t alpha=1.)
See TColor::SetPalette.
Definition TStyle.cxx:1889
virtual int GetMemInfo(MemInfo_t *info) const
Returns ram and swap memory usage info into the MemInfo_t structure.
Definition TSystem.cxx:2507
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
Int_t fMemFree
Definition TSystem.h:190