---
 util.c | 14 ++++++++++++++
 util.h | 18 ++++++++++++++++++
 2 files changed, 32 insertions(+)

diff --git a/util.c b/util.c
index 6bbbe91..e10cedc 100644
--- a/util.c
+++ b/util.c
@@ -512,3 +512,17 @@ void parray_extend(void ***a, ...)
        va_end(ap);
        (*a)[len - 1] = NULL;
 }
+
+int rate_limited(int interval, time_t *last)
+{
+       struct timespec ts;
+
+       if (clock_gettime(CLOCK_MONOTONIC, &ts))
+               return 1;
+       if (*last + interval > ts.tv_sec)
+               return 1;
+
+       *last = ts.tv_sec;
+
+       return 0;
+}
diff --git a/util.h b/util.h
index cc521b6..8ce2470 100644
--- a/util.h
+++ b/util.h
@@ -354,4 +354,22 @@ void parray_append(void ***a, void *p);
  */
 void parray_extend(void ***a, ...);
 
+/**
+ * Check if enough time has passed to implement a simple rate limiting.
+ *
+ * @param interval  Minimum interval between two calls returning 0 (in 
seconds).
+ * @param last      Time of the last call that returned 0, input/output.
+ * @return          1 when rate limited, 0 otherwise.
+ */
+int rate_limited(int interval, time_t *last);
+
+/* Convenient wrapper to limit the rate of some code */
+#define LIMIT_RATE(i, x...) \
+       do { \
+               static time_t last = -i; \
+               if (!rate_limited(i, &last)) { \
+                       x; \
+               } \
+       } while (0);
+
 #endif
-- 
2.1.0


------------------------------------------------------------------------------
_______________________________________________
Linuxptp-devel mailing list
Linuxptp-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/linuxptp-devel

Reply via email to