You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
100 lines
2.0 KiB
Plaintext
100 lines
2.0 KiB
Plaintext
#import "timer.h"
|
|
|
|
struct timespec subts(struct timespec t1, struct timespec t2) {
|
|
return (struct timespec) {
|
|
.tv_sec = t1.tv_sec - t2.tv_sec,
|
|
.tv_nsec = t1.tv_nsec - t2.tv_nsec,
|
|
};
|
|
}
|
|
|
|
struct timespec negts(struct timespec t) {
|
|
return (struct timespec) {
|
|
.tv_sec = -t.tv_sec,
|
|
.tv_nsec = -t.tv_nsec,
|
|
};
|
|
}
|
|
|
|
struct timespec addts(struct timespec t1, struct timespec t2) {
|
|
return (struct timespec) {
|
|
.tv_sec = t1.tv_sec + t2.tv_sec,
|
|
.tv_nsec = t1.tv_nsec + t2.tv_nsec,
|
|
};
|
|
}
|
|
|
|
void print_ts(struct timespec t) {
|
|
printf("time: %ld.%ld\n", (unsigned long)t.tv_sec, (unsigned long)t.tv_nsec);
|
|
}
|
|
|
|
double timespec_to_double(struct timespec ts) {
|
|
return ((double)(ts.tv_sec) + ((double)(ts.tv_nsec) / NSEC_PER_SEC));
|
|
}
|
|
|
|
@implementation Timer
|
|
-(id) init {
|
|
self = [super init];
|
|
running = false;
|
|
paused = false;
|
|
pause_start = {0};
|
|
pause_current = {0};
|
|
start = {0};
|
|
current = {0};
|
|
diff = {0};
|
|
return self;
|
|
}
|
|
|
|
-(void) start {
|
|
clock_gettime(CLOCK_REALTIME, &start);
|
|
running = true;
|
|
}
|
|
|
|
-(void) pause {
|
|
clock_gettime(CLOCK_REALTIME, &pause_start);
|
|
paused = true;
|
|
}
|
|
|
|
-(void) resume {
|
|
struct timespec t = subts(pause_current, pause_start);
|
|
diff = addts(diff, t);
|
|
paused = false;
|
|
}
|
|
|
|
-(void) stop {
|
|
running = false;
|
|
}
|
|
|
|
-(void) reset {
|
|
running = false;
|
|
start = (struct timespec){0};
|
|
current = start;
|
|
}
|
|
|
|
-(void) tick {
|
|
if (!paused) {
|
|
clock_gettime(CLOCK_REALTIME, ¤t);
|
|
} else {
|
|
clock_gettime(CLOCK_REALTIME, &pause_current);
|
|
//pause_current = subts(pause_current, pause_start);
|
|
}
|
|
}
|
|
|
|
-(struct timespec) time {
|
|
//time running = (current - start) - pause
|
|
struct timespec time = subts(current, start);
|
|
return subts(time, diff);
|
|
|
|
}
|
|
|
|
-(char *) timeString {
|
|
//super simple format
|
|
static char buffer[100];
|
|
struct timespec time = subts(current, start);
|
|
time = subts(time, diff);
|
|
|
|
double dbl = timespec_to_double(time);
|
|
|
|
sprintf(buffer, "%.02lf", dbl);
|
|
return buffer;
|
|
}
|
|
|
|
@end
|