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.
88 lines
1.8 KiB
Objective-C
88 lines
1.8 KiB
Objective-C
#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 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,
|
|
};
|
|
}
|
|
|
|
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 = (struct timespec){0};
|
|
pause_current = (struct timespec){0};
|
|
start = (struct timespec){0};
|
|
current = (struct timespec){0};
|
|
diff = (struct timespec){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);
|
|
}
|
|
}
|
|
|
|
-(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
|