Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timing rewrite #3

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion makefile
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ chp8-win: build/chp8-win.exe
build/chp8: $(SOURCES) mkdir
> $(CC) -O2 $(CFLAGS) $(CWARNINGS) $(CNOWARNINGS) $(ARGS) -o $@ $(SOURCES) $(LIBS)

build/chp8-win.exe: $(SOURCES_WIN) external/SDL2 mkdir
build/chp8-win.exe: $(SOURCES_WIN) external/SDL2 mkdir build/libwinpthread-1.dll
> $(CC_MINGW) -O2 $(CFLAGS_WIN) $(CWARNINGS) $(CNOWARNINGS) $(ARGS) -o $@ $(SOURCES_WIN) $(LIBS_WIN)

.PHONY: debug
Expand All @@ -41,3 +41,6 @@ clean:
external/SDL2:
> ./download_sdl_win.sh

build/libwinpthread-1.dll:
> ln -s /usr/x86_64-w64-mingw32/bin/libwinpthread-1.dll build/libwinpthread-1.dll

16 changes: 7 additions & 9 deletions timing.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,24 @@

#include "timing.h"

timing_t offset = 0;

timing_t now()
{
return clock() + offset;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
usec_t now = ts.tv_sec * USEC_PER_SEC + ts.tv_nsec / 1000;
return now;
}

timing_t hztotiming(int hz)
{
if(hz == 0)
return 0;
return CLOCKS_PER_SEC / hz;
return USEC_PER_SEC / hz;
}

int timingtos(timing_t tnow)
{
return tnow / CLOCKS_PER_SEC;
return tnow / USEC_PER_SEC;
}

// note:
Expand All @@ -31,16 +32,13 @@ int timingtos(timing_t tnow)
// usec_t now = ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
// usleep(start + target - now);

// TODO: consider using monotonic clock for timing
void sleepuntil(timing_t start, timing_t nap)
{
// better than the while loop that was here before,
// should still probably use monotonic clock instead
// maybe don't abuse now() calls and instead pass the
// frametime from main() to step() and from step()
// further down to input() and etc?
(void) start;
offset += nap;
usleep(nap * CLOCKS_PER_USEC);
usleep(nap);
}

5 changes: 3 additions & 2 deletions timing.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
#include <stdint.h>
#include <time.h>

#define CLOCKS_PER_USEC (CLOCKS_PER_SEC / 1000000ul)
#define USEC_PER_SEC (1000000ul)

typedef clock_t timing_t;
typedef uint64_t usec_t;
typedef usec_t timing_t;

timing_t now();
timing_t hztotiming(int hz);
Expand Down