# Timing a closure in Groovy

> Learn to easily time Groovy code execution with a custom timing closure, offering a simple yet powerful alternative to System.currentTimeMillis().

Author: [Guillaume Laforge](https://glaforge.dev/) | Published: 2004-02-26 | Topics: groovy | Canonical: https://glaforge.dev/posts/2004/02/26/timing-a-closure-in-groovy/


When you want to make some optimizations to your code, you often use the good old System.currentTimeMillis() method to time certain parts of your application. I wanted to do a similar thing when hacking some Groovy scripts recently, and the idea came to me that I could simply create a timing closure! So here it is, for your eyes only:

```groovy
timer = { closure ->
    start = System.currentTimeMillis()
    closure()
    println System.currentTimeMillis() - start
}
```

Then you can use your brand new timing closure:

```groovy
timer { "sleep 10".execute().waitFor() }
```

That's not rocket science, but closures are really a powerful feature. Everyday I wish Java had such a feature built-in.
