#!/usr/bin/env python

"""This script provides a benchmark for the JIT compiler, in
particular the speed of the in-memory cache."""

__author__ = "Anders Logg (logg@simula.no)"
__date__ = "2008-09-04"
__copyright__ = "Copyright (C) 2008-2010 Anders Logg"
__license__  = "GNU LGPL Version 2.1"

# Last changed: 2010-05-03

from dolfin import *
from time import time

print "JIT compilation (in memory cache)"

# Benchmark parameters
NUM_REPS = 10
SIZE = 3

# Create mesh
mesh = UnitCube(SIZE, SIZE, SIZE)

# Create form (velocity equation for "G2")
V = VectorFunctionSpace(mesh, "Lagrange", 1)
Q = FunctionSpace(mesh, "Lagrange", 1)
DG = FunctionSpace(mesh, "DG", 0)
DGv = VectorFunctionSpace(mesh, "DG", 0)

v  = TestFunction(V)
q  = TestFunction(Q)
u  = TrialFunction(V)
p  = TrialFunction(Q)
u0 = Function(V)
p1 = Function(Q)
W  = Function(DGv)
nu = Constant(0.1)
k  = Constant(0.1)
h  = CellSize(mesh)
d1 = h
d2 = 2.0*h

U = 0.5*(u0 + u)

F = (1.0/k)*inner(v, u - u0) + inner(v, grad(U)*W) + nu*inner(grad(v), grad(U)) - div(v)*p1 + \
    d1*inner(grad(v)*W, grad(U)*W) + d2*div(v)*div(U)
a = lhs(F*dx)

# JIT compile once
t0 = time()
jit(a)
t1 = time() - t0

# Then JIT compile some more
t0 = time()
for i in range(NUM_REPS):
    jit(a)
t2 = (time() - t0) / float(NUM_REPS)

print "Disk cache:     ", t1
print "In-memory cache:", t2
print "BENCH", t2
