André Buzzo
André Buzzo

Reputation: 31

Grails - How can I calculate execution time spent on any action?

I'm trying to measure time spent on every action of my application, since I'm rebuilding a legacy system.

Right now I'm doing this at Controller level:

def actionStart() {
    session.startTime = new Date().getTime()
}
def actionEnd() {
    def endTime = new Date().getTime()
    timeHandler(endTime, session.startTime)
}
def timeHandler(end, start){
    return end - start
}

Important: I want to move it to a Filter and automatically execute it at the start and ending of every action.

What should be the best approach? Thanks in advance.

PS.: What's the difference between getting System.currentTimeMillis() and instanciating an object? Performance?

Upvotes: 2

Views: 4958

Answers (4)

Jacob
Jacob

Reputation: 4031

You could do it with using methods afterInceptor and beforeInceptor

def actionArray = [:];

def afterInterceptor = {
        def time = System.currentTimeMillis() - actionArray[actionUri]
        println("Used time for action " + actionUri + "is: " + time + " ms");
    }

    def beforeInterceptor = {
        actionArray[actionUri] = System.currentTimeMillis();
}

Upvotes: 2

vector
vector

Reputation: 7576

This came up today, mentioned on DZone / GroovyMag: GProf is a profiler for Groovy

Upvotes: 1

Xeon
Xeon

Reputation: 5989

You should be able to use Grails filters to do this:

class TimeFilters {
    def filters = {
        timeCheck(controller: '*', action: '*') {
            before = { model ->
                ...
            }
            after = { model ->
                ...
            }
        }
    }
} 

If you look at the source code of java.util.Date:

public Date() {
    this(System.currentTimeMillis());
}

So this is just a performance overhead to create and get time: new Date().getTime()

Upvotes: 5

Alya'a Gamal
Alya'a Gamal

Reputation: 5638

At the start of the action do Like this :

long now = System.currentTimeMillis();

at the end of the Action , do Like this :

System.out.println( (System.currentTimeMillis() - now) + " ms");

and put your action between this two line

Disclaimer:

I answered this question according to java (before the tags was edited), so please clarify your tags.

Upvotes: 5

Related Questions