3.36 How to write jHepWork programs

As for Python, one should use the standard jHepWork libraries where possible, instead of creating unnecessary loops over primitive data types. There are two reasons for this: 1) less chance that one can make a mistake; 2) programs based on the standard Java libraries are a factor 5-10 faster.

Look at the 2 example below: the first program is very in inefficient (and long), while the second is a factor 6 faster (and shorter). Both programs fill a histogram with random numbers between 0 and 100 and show it in a frame.

# jHepWork. Program 1: 
from java.util import Random
from jhplot  import HPlot,H1D,HLabel
from time import clock

start=clock() # gives wallclock seconds, accuracy better than 1 ms

# build a histogram
h1 = H1D("This is a distribution",100, 0.0, 100.0)
rand = Random()

# fill histogram
for i in range(2000000):
   h1.fill(100*rand.nextDouble())

c1 = HPlot("Canvas",600,400)
c1.visible()
c1.setAutoRange()

c1.draw(h1)
send=clock()
#
print "Time elapsed = ", send - start, "seconds"
. The program below does the same, but it is faster by a factor 6:

# jHepWork: Program 2: 
from java.util import Random
from jhplot  import HPlot,H1D,HLabel
from time import clock
from jhplot.math.StatisticSample import randUniform

start=clock() # gives wallclock seconds, accuracy better than 1 ms

# fill histogram with random numbers 
h1 = H1D("This is a distribution",100, 0.0, 100.0)
h1.fill( randUniform(2000000,0.0,100.0) )

# draw
c1 = HPlot("Canvas",600,400)
c1.visible()
c1.setAutoRange()

c1.draw(h1)
send=clock()
#
print "Time elapsed = ", send - start, "seconds"
This program has the same speed as the equivalent ROOT/CINT macro shown below:

// Program 3: ROOT/CINT C++ program. 
#include <TStopwatch.h>
#include <TCanvas.h>
#include <TH1.h>

void test_root()
{
   TStopwatch sw;
   sw.Start();

   // Create a new canvas.
   c1 = new TCanvas("c1","Filling Example",0,0,600,400);
   hpx = new TH1F("hpx","This is a  distribution",100,0,100);

   for (int i=0; i<2000000; i++)
     hpx->Fill(100*gRandom->Rndm(1));

   hpx->Draw();
   sw.Stop();
   // stop timer and print results
   cout << "CPU time (sec)=" << sw.CpuTime() << endl;
   cout << "REAL time (sec)=" << sw.RealTime() << endl;
}
The reason why Program 2 has a speed similar to the CINT Program 3 is due to a longer Java start-up time needed to initialize the HPlot frame. If one fills the histogram with the random numbers, without building the frame, the Jython program 2 is faster by a factor 3 than the equivalent ROOT/CINT programs without any optimisation.