Skip to content

Instantly share code, notes, and snippets.

@opsJson
Last active January 4, 2022 17:44
Show Gist options
  • Select an option

  • Save opsJson/17e604500fed642ab0ede34773149c6b to your computer and use it in GitHub Desktop.

Select an option

Save opsJson/17e604500fed642ab0ede34773149c6b to your computer and use it in GitHub Desktop.
Easy time interface, with clear names. You can also execute a function with any number of arguments in a determined interval.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#include <windows.h>
#else
#include <unistd.h>
#define Sleep(time) sleep(time/1000)
#endif
#define MACRO void
MACRO setTimeout(int time, void (*function)(), ...) {}
#define setTimeout(time, function, ...) \
Sleep(time); function(__VA_ARGS__);
MACRO setInterval(int condition, int time, void (*function)(), ...) {}
#define setInterval(condition, time, function, ...) \
while (condition) {function(__VA_ARGS__); Sleep(time);}
MACRO printTime(clock_t start, clock_t end) {}
#define printTime(start, end) \
(float)(end - start) / CLOCKS_PER_SEC
#undef MACRO
typedef struct TIME {
int day;
int month;
int year;
int hour;
int minute;
int second;
int wday;
int yday;
int is_day;
} Time;
void updateTime(Time *time_s) {
if (time_s == NULL) return;
time_t t;
time(&t);
struct tm *time_tm;
time_tm = localtime(&t);
time_tm->tm_mon += 1;
time_tm->tm_year += 1900;
time_s->day = time_tm->tm_mday;
time_s->month = time_tm->tm_mon;
time_s->year = time_tm->tm_year;
time_s->hour = time_tm->tm_hour;
time_s->minute = time_tm->tm_min;
time_s->second = time_tm->tm_sec;
time_s->yday = time_tm->tm_yday;
time_s->wday = time_tm->tm_wday;
time_s->is_day = time_tm->tm_isdst;
}
Time* createTime() {
Time *time_s = (Time*)malloc(sizeof(Time));
updateTime(time_s);
return time_s;
}
/*///////////////////////////////////
Testing:
///////////////////////////////////*/
Time *t;
void foobar(char *str) {
updateTime(t);
printf("%s\n", str);
}
int main() {
clock_t start = clock();
t = createTime();
setInterval(t->second > 30, 1000 * 3, foobar, "foo");
setInterval(t->second <= 30, 1000 * 3, foobar, "bar");
free(t);
clock_t end = clock();
printf("%5.2fsec\n", printTime(start, end));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment