Created
April 3, 2012 21:34
Timer full code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
// A simple timer | |
type Timer time.Time | |
// Create and start a new timer | |
func StartTimer() Timer { | |
return Timer(time.Now()) | |
} | |
// A Nanosecond time value | |
type Nanosecond int64 | |
// Return the number of nanoseconds that have elapsed. | |
func (t Timer) ElapsedNanoseconds() Nanosecond { | |
return Nanosecond(time.Now().Sub(time.Time(t)).Nanoseconds()) | |
} | |
// A Millisecond time value | |
type Millisecond int64 | |
// Return the number of milliseconds that have elapsed. | |
func (t Timer) ElapsedMilliseconds() Millisecond { | |
return Millisecond(t.ElapsedNanoseconds() / 1000000) | |
} | |
// Convert Nanoseconds to Milliseconds | |
func (n Nanosecond) ToMilliseconds() Millisecond { | |
return Millisecond(n / 1000000) | |
} | |
// Convert Milliseconds to Nanoseconds | |
func (m Millisecond) ToNanoseconds() Nanosecond { | |
return Nanosecond(m * 1000000) | |
} | |
func main() { | |
timer0 := StartTimer() | |
time.Sleep(1000000000) // Sleep for one second | |
shortDelay := timer0.ElapsedNanoseconds() | |
timer1 := StartTimer() | |
time.Sleep(2 * 1000000000) // Sleep for two seconds | |
longDelay := timer1.ElapsedMilliseconds() | |
if shortDelay.ToMilliseconds() > longDelay { | |
fmt.Print("Something bad happened\n") | |
} | |
fmt.Print("Bubye!\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment