Skip to content

Instantly share code, notes, and snippets.

@filiptronicek
Created July 23, 2024 12:08
Show Gist options
  • Save filiptronicek/664a675ba37cdcbdadcffc3476d8334e to your computer and use it in GitHub Desktop.
Save filiptronicek/664a675ba37cdcbdadcffc3476d8334e to your computer and use it in GitHub Desktop.
Testing file notification latency
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"time"
"github.com/fsnotify/fsnotify"
)
func main() {
timeChannel := make(chan time.Time, 1)
go func() {
currentTime := time.Now()
err := ioutil.WriteFile("sample.txt", []byte(currentTime.String()), 0644)
if err != nil {
log.Fatalf("Failed to write to file: %v", err)
}
fmt.Printf("Written to file at: %v\n", currentTime.UnixNano())
timeChannel <- currentTime
}()
go func() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalf("Failed to create file watcher: %v", err)
}
defer watcher.Close()
err = watcher.Add("./sample.txt")
if err != nil {
log.Fatalf("Failed to add file to watcher: %v", err)
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
notificationTime := time.Now()
writeTime := <-timeChannel
timeDiff := notificationTime.Sub(writeTime)
fmt.Printf("File change notification at: %v, time taken: %v ns\n", notificationTime.UnixNano(), timeDiff.Nanoseconds())
os.Exit(0)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Printf("Error watching file: %v\n", err)
}
}
}()
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment