shithub: femtolisp

ref: 54d451808fafb72fdc70df17f4b811968b04bbbd
dir: /time_plan9.c/

View raw version
#include "llt.h"
#include "timefuncs.h"
#include <tos.h>

double
sec_realtime(void)
{
	vlong t = nsec();
	vlong ns = t % 1000000000LL;
	vlong s = (t - ns) / 1000000000LL;
	return (double)s + (double)ns/1.0e9;
}

/*
 * nsec() is wallclock and can be adjusted by timesync
 * so need to use cycles() instead, but fall back to
 * nsec() in case we can't
 */
uint64_t
nanosec_monotonic(void)
{
	static uint64_t fasthz, xstart;
	uint64_t x, div;

	if(fasthz == ~0ULL)
		return nsec() - xstart;

	if(fasthz == 0){
		if(_tos->cyclefreq){
			fasthz = _tos->cyclefreq;
			cycles(&xstart);
		} else {
			fasthz = ~0ULL;
			xstart = nsec();
		}
		return 0;
	}
	cycles(&x);
	x -= xstart;

	/* this is ugly */
	for(div = 1000000000ULL; x < 0x1999999999999999ULL && div > 1 ; div /= 10ULL, x *= 10ULL);

	return x / (fasthz / div);
}

void
timestring(double s, char *buf, int sz)
{
	Tm tm;
	snprint(buf, sz, "%τ", tmfmt(tmtime(&tm, s, tzload("local")), nil));
}

double
parsetime(const char *s)
{
	Tm tm;
	if(tmparse(&tm, "?WWW, ?MM ?DD hh:mm:ss ?Z YYYY", s, tzload("local"), nil) == nil)
		return -1;
	return tmnorm(&tm);
}

void
sleep_ms(int ms)
{
	if(ms != 0)
		sleep(ms);
}