Created
July 23, 2024 12:08
-
-
Save filiptronicek/664a675ba37cdcbdadcffc3476d8334e to your computer and use it in GitHub Desktop.
Testing file notification latency
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" | |
"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