shithub: lu9-p9

Download patch

ref: f61a1482c51e55d2d03c57006f71219163b507cd
parent: c93c5dddf7ad739507e3ae5a3588df8f51d6fe3d
author: kvik <kvik@a-b.xyz>
date: Sat Aug 7 20:17:55 EDT 2021

base: add p9.nsec and p9.nanosec functions

--- a/base/base.c
+++ b/base/base.c
@@ -1,6 +1,7 @@
 #include <u.h>
 #include <libc.h>
 #include <ctype.h>
+#include <tos.h>
 
 #include <lua.h>
 #include <lauxlib.h>
@@ -48,6 +49,8 @@
 	{"user", p9_user},
 	{"sysname", p9_sysname},
 	
+	{"nanosec", p9_nanosec},
+	{"nsec", p9_nsec},
 	{"cleanname", p9_cleanname},
 	
 	{nil, nil}
--- a/base/misc.c
+++ b/base/misc.c
@@ -15,3 +15,46 @@
 	lua_pushstring(L, p);
 	return 1;
 }
+
+/* Taken from treason(1), thanks sigrid */
+static uvlong
+nanosec(void)
+{
+	static uvlong fasthz, xstart;
+	uvlong x, div;
+
+	if(fasthz == ~0ULL)
+		return nsec() - xstart;
+
+	if(fasthz == 0){
+		fasthz = _tos->cyclefreq;
+		if(fasthz == 0){
+			fasthz = ~0ULL;
+			xstart = nsec();
+		}else{
+			cycles(&xstart);
+		}
+		return 0;
+	}
+	cycles(&x);
+	x -= xstart;
+
+	/* this is ugly */
+	for(div = 1000000000ULL; x < 0x1999999999999999ULL && div > 1 ; div /= 10ULL, x *= 10ULL);
+
+	return x / (fasthz / div);
+}
+
+static int
+p9_nanosec(lua_State *L)
+{
+	lua_pushinteger(L, nanosec());
+	return 1;
+}
+
+static int
+p9_nsec(lua_State *L)
+{
+	lua_pushinteger(L, nsec());
+	return 1;
+}