Varun
Varun

Reputation: 35

Time difference in Groovy

I am trying to print start & end time of stage in pipeline along with time taken for completing stage. Not getting expected result.

script{def start_time = new Date()
echo "Start Date: ${start_time}"                
sleep time: 2, unit: 'MINUTES'
def end_time = new Date()
def total_time = end_time - start_time
echo "End Date: ${end_time}"
echo "Total Time: ${total_time}"}

Upvotes: 1

Views: 868

Answers (2)

willyjoker
willyjoker

Reputation: 877

Use TimeDuration and TimeCategory :

import groovy.time.* // I don't remember whether Jenkins pipelines do this differently

//your stuff

TimeDuration duration = TimeCategory.minus(end_time, start_time)

echo "Total Time: ${duration}"
//something like "Total Time: 2.063 seconds"

Printing duration will give you a human-readable representation. You can also do duration.toMilliseconds() if you need a numeric value for calculations, metrics, etc.

Upvotes: 0

cfrick
cfrick

Reputation: 37033

Subtracting dates in groovy will give you the duration in days - most likely your jobs are not running that long.

Instead use e.g. System.currentTimeSeconds() to calculate the duration in seconds.

Upvotes: 2

Related Questions