Elapsed Time:
The easiest way to get the elapsed time from a specific time ( start ) is to use the time.Since() function, which returns the time.Duration , which has the Duration.Seconds() method, which returns the duration in seconds as float64 .
So, in your case, the elapsed seconds:
sec := time.Since(start).Seconds()
Now for testing ...
When testing sleeping functions, you should consider that after sleep it is not guaranteed that the code will continue to be executed immediately. For example, quoting from the document time.Sleep() :
Sleep pauses the current goroutine for at least duration d.
So, when writing test code for functions like sleep, I would test the following:
- Elapsed time must be at least indicated
- and suppose some error field.
So, for example, check this as follows:
func TestSleep(t *testing.T) { const secSleep = 65.0 start := time.Now() mySleepFunction(int(secSleep)) sec := time.Since(start).Seconds() if sec < secSleep || sec > secSleep*1.05 { t.Error("Incorrect sleep function") } }
source share