static void test_mutex_timed(void) { struct TestMutexTimedData data; thrd_t thread; struct timespec interval = { 0, }; struct timespec start; struct timespec end; interval.tv_sec = 0; interval.tv_nsec = (NSECS_PER_SECOND / 10) * 2; mtx_init(&(data.mutex), mtx_timed); mtx_lock(&(data.mutex)); timespec_get(&(data.start), TIME_UTC); data.timeout = data.start; timespec_add_nsec(&(data.timeout), NSECS_PER_SECOND / 10); data.end = data.timeout; timespec_add_nsec(&(data.end), NSECS_PER_SECOND / 10); data.upper = data.end; timespec_add_nsec(&(data.upper), NSECS_PER_SECOND / 10); thrd_create(&thread, test_mutex_timed_thread_func, &data); timespec_get(&start, TIME_UTC); assert (thrd_sleep(&interval, &interval) == 0); timespec_get(&end, TIME_UTC); mtx_unlock(&(data.mutex)); thrd_join(thread, NULL); }
int thrd_sleep(const struct timespec *duration, struct timespec *remaining) { #if !defined(_TTHREAD_WIN32_) return nanosleep(duration, remaining); #else struct timespec start; DWORD t; timespec_get(&start, TIME_UTC); t = SleepEx((DWORD)(duration->tv_sec * 1000 + duration->tv_nsec / 1000000 + (((duration->tv_nsec % 1000000) == 0) ? 0 : 1)), TRUE); if (t == 0) { return 0; } else if (remaining != NULL) { timespec_get(remaining, TIME_UTC); remaining->tv_sec -= start.tv_sec; remaining->tv_nsec -= start.tv_nsec; if (remaining->tv_nsec < 0) { remaining->tv_nsec += 1000000000; remaining->tv_sec -= 1; } } else { return -1; } return 0; #endif }
static int test_mutex_timed_thread_func(void* arg) { int ret; struct timespec ts; struct TestMutexTimedData* data = (struct TestMutexTimedData*) arg; ret = mtx_timedlock(&(data->mutex), &(data->timeout)); assert (ret == thrd_timedout); timespec_get(&ts, TIME_UTC); ret = timespec_compare(&ts, &(data->start)); assert (ret >= 0); ret = timespec_compare(&ts, &(data->timeout)); assert (ret >= 0); ret = timespec_compare(&ts, &(data->end)); assert (ret < 0); ret = mtx_lock(&(data->mutex)); assert (ret == thrd_success); timespec_get(&ts, TIME_UTC); ret = timespec_compare(&ts, &(data->end)); assert (ret >= 0); ret = timespec_compare(&ts, &(data->upper)); assert (ret < 0); mtx_unlock(&(data->mutex)); return 0; }
double get_secs(void) { struct timespec ts; /* C11. Use this so we can get completely rid of SDL to benchmark the CPU. */ timespec_get(&ts, TIME_UTC); return ts.tv_sec + (1e-9 * ts.tv_nsec); /*return SDL_GetTicks() / 1000.0;*/ }
double ltfat_time() { struct timespec ts; timespec_get(&ts, TIME_UTC); return (1000.0 * ((double)tv.tv_sec) + ((double)tv.tv_nsec) / 1000000.0); }
static int windows_clock_gettime(int clk_id, struct timespec *tp) { struct timer_request request; #if !defined(_MSC_VER) || (_MSC_VER < 1900) FILETIME filetime; ULARGE_INTEGER rtime; #endif DWORD r; switch (clk_id) { case USBI_CLOCK_MONOTONIC: if (timer_thread) { request.tp = tp; request.event = CreateEvent(NULL, FALSE, FALSE, NULL); if (request.event == NULL) return LIBUSB_ERROR_NO_MEM; if (!pPostThreadMessageA(timer_thread_id, WM_TIMER_REQUEST, 0, (LPARAM)&request)) { usbi_err(NULL, "PostThreadMessage failed for timer thread: %s", windows_error_str(0)); CloseHandle(request.event); return LIBUSB_ERROR_OTHER; } do { r = WaitForSingleObject(request.event, TIMER_REQUEST_RETRY_MS); if (r == WAIT_TIMEOUT) usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?"); else if (r == WAIT_FAILED) usbi_err(NULL, "WaitForSingleObject failed: %s", windows_error_str(0)); } while (r == WAIT_TIMEOUT); CloseHandle(request.event); if (r == WAIT_OBJECT_0) return LIBUSB_SUCCESS; else return LIBUSB_ERROR_OTHER; } // Fall through and return real-time if monotonic was not detected @ timer init case USBI_CLOCK_REALTIME: #if defined(_MSC_VER) && (_MSC_VER >= 1900) timespec_get(tp, TIME_UTC); #else // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx // with a predef epoch time to have an epoch that starts at 1970.01.01 00:00 // Note however that our resolution is bounded by the Windows system time // functions and is at best of the order of 1 ms (or, usually, worse) GetSystemTimeAsFileTime(&filetime); rtime.LowPart = filetime.dwLowDateTime; rtime.HighPart = filetime.dwHighDateTime; rtime.QuadPart -= EPOCH_TIME; tp->tv_sec = (long)(rtime.QuadPart / 10000000); tp->tv_nsec = (long)((rtime.QuadPart % 10000000) * 100); #endif return LIBUSB_SUCCESS; default: return LIBUSB_ERROR_INVALID_PARAM; } }
int main() { struct timespec ts; if( timespec_get( &ts, TIME_UTC) != 0) printf("The exact local time:\n" "%.24s and %09lu nanoseconds\n", ctime(&ts.tv_sec), ts.tv_nsec); return 0; }
static void test_sleep(void) { struct timespec ts; struct timespec interval; struct timespec end_ts; interval.tv_sec = 0; interval.tv_nsec = NSECS_PER_SECOND / 10; /* Calculate current time + 100ms */ timespec_get(&ts, TIME_UTC); timespec_add_nsec(&ts, NSECS_PER_SECOND / 10); /* Sleep... */ thrd_sleep(&interval, NULL); timespec_get(&end_ts, TIME_UTC); assert(timespec_compare(&ts, &end_ts) <= 0); }
void timespec_update(struct timespec *time) { assert(time != NULL); #if defined(_POSIX_C_SOURCE) if (clock_gettime(CLOCK_BOOTTIME, time)) error("clock_gettime"); #else if (!timespec_get(time, TIME_UTC)) error("timespec_get"); #endif }
int thrd_sleep(const struct timespec *duration, struct timespec *remaining) { #if !defined(_TTHREAD_WIN32_) int res = nanosleep(duration, remaining); if (res == 0) { return 0; } else if (errno == EINTR) { return -1; } else { return -2; } #else struct timespec start; DWORD t; timespec_get(&start, TIME_UTC); t = SleepEx((DWORD)(duration->tv_sec * 1000 + duration->tv_nsec / 1000000 + (((duration->tv_nsec % 1000000) == 0) ? 0 : 1)), TRUE); if (t == 0) { return 0; } else { if (remaining != NULL) { timespec_get(remaining, TIME_UTC); remaining->tv_sec -= start.tv_sec; remaining->tv_nsec -= start.tv_nsec; if (remaining->tv_nsec < 0) { remaining->tv_nsec += 1000000000; remaining->tv_sec -= 1; } } return (t == WAIT_IO_COMPLETION) ? -1 : -2; } #endif }
/*! Prints out current hour, minute, second, and 10th of a second as null terminated string into given buffer @param time_string Buffer to write time string into, at least 32 bytes long @attention Buffer must be at least 32 bytes long. @return Also returns a pointer to the given buffer */ char* display_time (char *time_string) { time_t t = time(NULL); struct tm tm; localtime_r(&t, &tm); struct timespec ts; #ifdef __MACH__ clock_gettime(CLOCK_REALTIME,&ts); #else timespec_get(&ts, TIME_UTC); #endif sprintf(time_string,"%d h %d min %d.%.0f sec \n",tm.tm_hour,tm.tm_min,tm.tm_sec,ts.tv_nsec / (float)100000000); return time_string; }
static struct mrb_time* current_mrb_time(mrb_state *mrb) { struct mrb_time *tm; tm = (struct mrb_time *)mrb_malloc(mrb, sizeof(*tm)); #if defined(TIME_UTC) { struct timespec ts; if (timespec_get(&ts, TIME_UTC) == 0) { mrb_free(mrb, tm); mrb_raise(mrb, E_RUNTIME_ERROR, "timespec_get() failed for unknown reasons"); } tm->sec = ts.tv_sec; tm->usec = ts.tv_nsec / 1000; } #elif defined(NO_GETTIMEOFDAY) { static time_t last_sec = 0, last_usec = 0; tm->sec = time(NULL); if (tm->sec != last_sec) { last_sec = tm->sec; last_usec = 0; } else { /* add 1 usec to differentiate two times */ last_usec += 1; } tm->usec = last_usec; } #else { struct timeval tv; gettimeofday(&tv, NULL); tm->sec = tv.tv_sec; tm->usec = tv.tv_usec; } #endif tm->timezone = MRB_TIMEZONE_LOCAL; mrb_time_update_datetime(tm); return tm; }
double currentTime(void) { double ans = NA_REAL; #ifdef HAVE_TIMESPEC_GET struct timespec tp; int res = timespec_get(&tp, TIME_UTC); if(res != 0) ans = (double) tp.tv_sec + 1e-9 * (double) tp.tv_nsec; #elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_REALTIME) /* Has 2038 issue if time_t: tv.tv_sec is 32-bit. */ struct timespec tp; int res = clock_gettime(CLOCK_REALTIME, &tp); if(res == 0) ans = (double) tp.tv_sec + 1e-9 * (double) tp.tv_nsec; #elif defined(HAVE_GETTIMEOFDAY) /* Mac OS X, mingw.org, used on mingw-w64. Has 2038 issue if time_t: tv.tv_sec is 32-bit. */ struct timeval tv; int res = gettimeofday(&tv, NULL); if(res == 0) ans = (double) tv.tv_sec + 1e-6 * (double) tv.tv_usec; #else /* No known current OSes */ time_t res = time(NULL); if(res != (time_t)(-1)) /* -1 must be an error as the real value -1 was ca 1969 */ ans = (double) res; #endif #ifndef HAVE_POSIX_LEAPSECONDS /* No known current OSes */ /* Disallowed by POSIX (1988-): http://www.mail-archive.com/[email protected]/msg00109.html http://en.wikipedia.org/wiki/Unix_time */ if (!ISNAN(ans)) { ans -= n_leapseconds; } #endif return ans; }
int func(void * thrd) { struct timespec ts; timespec_get( &ts, TIME_UTC); // The current time; ts.tv_sec += 3; // 3 seconds from now. printf("%s waiting ...\n", (char*)thrd); int res = mtx_timedlock(&mtx, &ts); switch(res) { case thrd_success: puts("Obtained mutex\n... releasing ..."); mtx_unlock(&mtx); break; case thrd_timedout: puts("Timed out."); break; default: puts("mtx_timedlock: error."); }; return res; }
int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) { #if defined(_TTHREAD_WIN32_) struct timespec now; if (timespec_get(&now, TIME_UTC) == 0) { DWORD delta = (DWORD)((ts->tv_sec - now.tv_sec) * 1000 + (ts->tv_nsec - now.tv_nsec + 500000) / 1000000); return _cnd_timedwait_win32(cond, mtx, delta); } else return thrd_error; #else int ret; ret = pthread_cond_timedwait(cond, mtx, ts); if (ret == ETIMEDOUT) { return thrd_timedout; } return ret == 0 ? thrd_success : thrd_error; #endif }
int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) { #if defined(_TTHREAD_WIN32_) struct timespec now; if (timespec_get(&now, TIME_UTC) == TIME_UTC) { unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000; unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000; DWORD delta = (tsInMilliseconds > nowInMilliseconds) ? (DWORD)(tsInMilliseconds - nowInMilliseconds) : 0; return _cnd_timedwait_win32(cond, mtx, delta); } else return thrd_error; #else int ret; ret = pthread_cond_timedwait(cond, mtx, ts); if (ret == ETIMEDOUT) { return thrd_timedout; } return ret == 0 ? thrd_success : thrd_error; #endif }
static void test_time(void) { struct timespec ts; timespec_get(&ts, TIME_UTC); }
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) { #if defined(_TTHREAD_WIN32_) struct timespec current_ts; DWORD timeoutMs; if (!mtx->mTimed) { return thrd_error; } timespec_get(¤t_ts, TIME_UTC); if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec))) { timeoutMs = 0; } else { timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000; timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000; timeoutMs += 1; } /* TODO: the timeout for WaitForSingleObject doesn't include time while the computer is asleep. */ switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs)) { case WAIT_OBJECT_0: break; case WAIT_TIMEOUT: return thrd_timedout; case WAIT_ABANDONED: default: return thrd_error; } if (!mtx->mRecursive) { while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ mtx->mAlreadyLocked = TRUE; } return thrd_success; #elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L) switch (pthread_mutex_timedlock(mtx, ts)) { case 0: return thrd_success; case ETIMEDOUT: return thrd_timedout; default: return thrd_error; } #else int rc; struct timespec cur, dur; /* Try to acquire the lock and, if we fail, sleep for 5ms. */ while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) { timespec_get(&cur, TIME_UTC); if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec))) { break; } dur.tv_sec = ts->tv_sec - cur.tv_sec; dur.tv_nsec = ts->tv_nsec - cur.tv_nsec; if (dur.tv_nsec < 0) { dur.tv_sec--; dur.tv_nsec += 1000000000; } if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000)) { dur.tv_sec = 0; dur.tv_nsec = 5000000; } nanosleep(&dur, NULL); } switch (rc) { case 0: return thrd_success; case ETIMEDOUT: case EBUSY: return thrd_timedout; default: return thrd_error; } #endif }
int vout_snapshot_SaveImage(char **name, int *sequential, const block_t *image, vout_thread_t *p_vout, const vout_snapshot_save_cfg_t *cfg) { /* */ char *filename; DIR *pathdir = vlc_opendir(cfg->path); input_thread_t *input = (input_thread_t*)p_vout->p->input; if (pathdir != NULL) { /* The use specified a directory path */ closedir(pathdir); /* */ char *prefix = NULL; if (cfg->prefix_fmt) prefix = str_format(input, cfg->prefix_fmt); if (prefix) filename_sanitize(prefix); else { prefix = strdup("vlcsnap-"); if (!prefix) goto error; } if (cfg->is_sequential) { for (int num = cfg->sequence; ; num++) { struct stat st; if (asprintf(&filename, "%s" DIR_SEP "%s%05d.%s", cfg->path, prefix, num, cfg->format) < 0) { free(prefix); goto error; } if (vlc_stat(filename, &st)) { *sequential = num; break; } free(filename); } } else { struct timespec ts; struct tm curtime; char buffer[128]; timespec_get(&ts, TIME_UTC); if (localtime_r(&ts.tv_sec, &curtime) == NULL) gmtime_r(&ts.tv_sec, &curtime); if (strftime(buffer, sizeof(buffer), "%Y-%m-%d-%Hh%Mm%Ss", &curtime) == 0) strcpy(buffer, "error"); if (asprintf(&filename, "%s" DIR_SEP "%s%s%03lu.%s", cfg->path, prefix, buffer, ts.tv_nsec / 1000000, cfg->format) < 0) filename = NULL; } free(prefix); } else { /* The user specified a full path name (including file name) */ filename = str_format(input, cfg->path); path_sanitize(filename); } if (!filename) goto error; /* Save the snapshot */ FILE *file = vlc_fopen(filename, "wb"); if (!file) { msg_Err(p_vout, "Failed to open '%s'", filename); free(filename); goto error; } if (fwrite(image->p_buffer, image->i_buffer, 1, file) != 1) { msg_Err(p_vout, "Failed to write to '%s'", filename); fclose(file); free(filename); goto error; } fclose(file); /* */ if (name) *name = filename; else free(filename); return VLC_SUCCESS; error: msg_Err(p_vout, "could not save snapshot"); return VLC_EGENERIC; }
void GBSerialize(struct GB* gb, struct GBSerializedState* state) { STORE_32LE(GB_SAVESTATE_MAGIC + GB_SAVESTATE_VERSION, 0, &state->versionMagic); STORE_32LE(gb->romCrc32, 0, &state->romCrc32); if (gb->memory.rom) { memcpy(state->title, ((struct GBCartridge*) gb->memory.rom)->titleLong, sizeof(state->title)); } else { memset(state->title, 0, sizeof(state->title)); } state->model = gb->model; state->cpu.a = gb->cpu->a; state->cpu.f = gb->cpu->f.packed; state->cpu.b = gb->cpu->b; state->cpu.c = gb->cpu->c; state->cpu.d = gb->cpu->d; state->cpu.e = gb->cpu->e; state->cpu.h = gb->cpu->h; state->cpu.l = gb->cpu->l; STORE_16LE(gb->cpu->sp, 0, &state->cpu.sp); STORE_16LE(gb->cpu->pc, 0, &state->cpu.pc); STORE_32LE(gb->cpu->cycles, 0, &state->cpu.cycles); STORE_32LE(gb->cpu->nextEvent, 0, &state->cpu.nextEvent); STORE_16LE(gb->cpu->index, 0, &state->cpu.index); state->cpu.bus = gb->cpu->bus; state->cpu.executionState = gb->cpu->executionState; STORE_16LE(gb->cpu->irqVector, 0, &state->cpu.irqVector); STORE_32LE(gb->eiPending, 0, &state->cpu.eiPending); GBSerializedCpuFlags flags = 0; flags = GBSerializedCpuFlagsSetCondition(flags, gb->cpu->condition); flags = GBSerializedCpuFlagsSetIrqPending(flags, gb->cpu->irqPending); flags = GBSerializedCpuFlagsSetDoubleSpeed(flags, gb->doubleSpeed); STORE_32LE(flags, 0, &state->cpu.flags); GBMemorySerialize(&gb->memory, state); GBIOSerialize(gb, state); GBVideoSerialize(&gb->video, state); GBTimerSerialize(&gb->timer, state); GBAudioSerialize(&gb->audio, state); #ifndef _MSC_VER struct timeval tv; if (!gettimeofday(&tv, 0)) { uint64_t usec = tv.tv_usec; usec += tv.tv_sec * 1000000LL; STORE_64LE(usec, 0, &state->creationUsec); } #else struct timespec ts; if (timespec_get(&ts, TIME_UTC)) { uint64_t usec = ts.tv_nsec / 1000; usec += ts.tv_sec * 1000000LL; STORE_64LE(usec, 0, &state->creationUsec); } #endif else { state->creationUsec = 0; } }
void GBASerialize(struct GBA* gba, struct GBASerializedState* state) { STORE_32(GBA_SAVESTATE_MAGIC + GBA_SAVESTATE_VERSION, 0, &state->versionMagic); STORE_32(gba->biosChecksum, 0, &state->biosChecksum); STORE_32(gba->romCrc32, 0, &state->romCrc32); if (gba->memory.rom) { state->id = ((struct GBACartridge*) gba->memory.rom)->id; memcpy(state->title, ((struct GBACartridge*) gba->memory.rom)->title, sizeof(state->title)); } else { state->id = 0; memset(state->title, 0, sizeof(state->title)); } int i; for (i = 0; i < 16; ++i) { STORE_32(gba->cpu->gprs[i], i * sizeof(state->cpu.gprs[0]), state->cpu.gprs); } STORE_32(gba->cpu->cpsr.packed, 0, &state->cpu.cpsr.packed); STORE_32(gba->cpu->spsr.packed, 0, &state->cpu.spsr.packed); STORE_32(gba->cpu->cycles, 0, &state->cpu.cycles); STORE_32(gba->cpu->nextEvent, 0, &state->cpu.nextEvent); for (i = 0; i < 6; ++i) { int j; for (j = 0; j < 7; ++j) { STORE_32(gba->cpu->bankedRegisters[i][j], (i * 7 + j) * sizeof(gba->cpu->bankedRegisters[0][0]), state->cpu.bankedRegisters); } STORE_32(gba->cpu->bankedSPSRs[i], i * sizeof(gba->cpu->bankedSPSRs[0]), state->cpu.bankedSPSRs); } STORE_32(gba->memory.biosPrefetch, 0, &state->biosPrefetch); STORE_32(gba->cpu->prefetch[0], 0, state->cpuPrefetch); STORE_32(gba->cpu->prefetch[1], 4, state->cpuPrefetch); STORE_32(gba->memory.lastPrefetchedPc, 0, &state->lastPrefetchedPc); GBASerializedMiscFlags miscFlags = 0; miscFlags = GBASerializedMiscFlagsSetHalted(miscFlags, gba->cpu->halted); STORE_32(miscFlags, 0, &state->miscFlags); GBAMemorySerialize(&gba->memory, state); GBAIOSerialize(gba, state); GBAVideoSerialize(&gba->video, state); GBAAudioSerialize(&gba->audio, state); GBASavedataSerialize(&gba->memory.savedata, state); #ifndef _MSC_VER struct timeval tv; if (!gettimeofday(&tv, 0)) { uint64_t usec = tv.tv_usec; usec += tv.tv_sec * 1000000LL; STORE_64(usec, 0, &state->creationUsec); } #else struct timespec ts; if (timespec_get(&ts, TIME_UTC)) { uint64_t usec = ts.tv_nsec / 1000; usec += ts.tv_sec * 1000000LL; STORE_64(usec, 0, &state->creationUsec); } #endif else { state->creationUsec = 0; } state->associatedStreamId = 0; if (gba->rr) { gba->rr->stateSaved(gba->rr, state); } }
/** * Returns the current time in microsecond resolution. Suitable for performance timing. */ static long get_micros() { struct timespec ts; timespec_get(&ts, TIME_UTC); return (long) ts.tv_sec * 1000000L + ts.tv_nsec / 1000L; }
static int tests_run(const Test* tests, int argc, char** argv) { int opt; unsigned long int seed; char* endptr; struct timespec tv; int test_n; int found; timespec_get(&tv, TIME_UTC); srand(tv.tv_nsec); seed = rand(); #if !defined(_TTHREAD_WIN32_) while ((opt = getopt(argc, argv, "s:h")) != -1) { switch (opt) { case 's': { seed = strtoul(optarg, &endptr, 0); if (*endptr != '\0' || seed > UINT_MAX) { fprintf (stdout, "Invalid seed `%s'.\n", optarg); exit(-1); } } break; case 'h': test_config_print_and_exit(tests, argc, argv); return 0; default: test_config_print_and_exit(tests, argc, argv); return -1; } } fprintf(stdout, "Random seed: %lu\n", seed); if (optind < argc) { for (; optind < argc; optind++) { found = 0; for (test_n = 0; tests[test_n].name != NULL; test_n++) { if (strcasecmp(argv[optind], tests[test_n].name) == 0) { test_run (&(tests[test_n]), seed); found = 1; break; } } if (found == 0) { fprintf (stderr, "Could not find test `%s'.\n", argv[optind]); exit(-1); } } return 0; } #endif for (test_n = 0; tests[test_n].name != NULL; test_n++) { test_run (&(tests[test_n]), seed); } return 0; }
int main(int argc, const char **argv){ char buffer[4096]; /* According to http://stackoverflow.com/a/2879610/167486 POSIX suggests a line length of 4096 */ double interval = 1.0; char *pend = NULL; int c = 0; const char *freqs = NULL; double freq = 0; #ifdef USE_TIMESPEC struct timespec last; struct timespec now; #else time_t last = 0; time_t now = 0; #endif for (c = 1 ; c < argc ; ++c) { if (strcmp(argv[c], "--version") == 0) { version(); return 0; } if (strcmp(argv[c], "--help") == 0) { usage(); return 0; } else if ((c < argc - 1 && (strcmp(argv[c], "-f") == 0 || strcmp(argv[c], "--frequency") == 0)) || (argv[c][0] == '-' && argv[c][1] == 'f' && argv[c][2] >= '0' && argv[c][2] <= '9')) { if (argv[c][2] >= '0' && argv[c][2] <= '9') { freqs = &argv[c][2]; } else { freqs = argv[c + 1]; } freq = strtod(freqs, &pend); if (freq < DBL_EPSILON) { fprintf(stderr, "Frequency argument %f is out of range (expected a floating-point number larger than 0)\n", freq); usage(); return 1; } else if (pend == NULL || *pend != '\0') { fprintf(stderr, "Could not parse frequency argument %s (expected an floating-point number larger than 0)\n", argv[c + 1]); usage(); return 1; } interval = 1.0 / freq; c += 1; } else { fprintf(stderr, "Unrecognized argument %s\n", argv[c]); usage(); return 1; } } setvbuf(stdout,NULL,_IOLBF,256); while (fgets(buffer, sizeof(buffer), stdin) != NULL) { #ifdef USE_TIMESPEC timespec_get(&now, TIME_UTC); if (difftimespec(&now, &last) >= interval) { #else time(&now); if (difftime(now, last) >= interval) { #endif puts(buffer); last = now; } } return 0; }
int main(int argc, char** argv) { bool cpu_stats = false; bool mem_stats = false; zx_duration_t delay = ZX_SEC(1); int num_loops = -1; bool timestamp = false; int c; while ((c = getopt(argc, argv, "cd:n:hmt")) > 0) { switch (c) { case 'c': cpu_stats = true; break; case 'd': delay = ZX_SEC(atoi(optarg)); if (delay == 0) { fprintf(stderr, "Bad -d value '%s'\n", optarg); print_help(stderr); return 1; } break; case 'n': num_loops = atoi(optarg); if (num_loops == 0) { fprintf(stderr, "Bad -n value '%s'\n", optarg); print_help(stderr); return 1; } break; case 'h': print_help(stdout); return 0; case 'm': mem_stats = true; break; case 't': timestamp = true; break; default: fprintf(stderr, "Unknown option\n"); print_help(stderr); return 1; } } if (!cpu_stats && !mem_stats) { fprintf(stderr, "No statistics selected\n"); print_help(stderr); return 1; } zx_handle_t root_resource; zx_status_t ret = get_root_resource(&root_resource); if (ret != ZX_OK) { return ret; } // set stdin to non blocking so we can intercept ctrl-c. // TODO: remove once ctrl-c works in the shell fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); for (;;) { zx_time_t next_deadline = zx_deadline_after(delay); // Print the current UTC time with milliseconds as // an ISO 8601 string. if (timestamp) { struct timespec now; timespec_get(&now, TIME_UTC); struct tm nowtm; gmtime_r(&now.tv_sec, &nowtm); char tbuf[40]; strftime(tbuf, sizeof(tbuf), "%FT%T", &nowtm); printf("\n--- %s.%03ldZ ---\n", tbuf, now.tv_nsec / (1000 * 1000)); } if (cpu_stats) { ret |= cpustats(root_resource, delay); } if (mem_stats) { ret |= memstats(root_resource); } if (ret != ZX_OK) break; if (num_loops > 0) { if (--num_loops == 0) { break; } } else { // TODO: replace once ctrl-c works in the shell char c; int err; while ((err = read(STDIN_FILENO, &c, 1)) > 0) { if (c == 0x3) return 0; } } zx_nanosleep(next_deadline); } zx_handle_close(root_resource); return ret; }
int main(int argc, char* argv[]) { if (argc < 2) { printf("Usage: %s METHOD\n", argv[0]); return -1; } printf("Hash size is: %d\n", HASH_BYTES); struct timespec start_time, end_time; timespec_get(&start_time, TIME_UTC); srand((unsigned int)time(NULL)); hash_t m1; hash_t m2; if (strcmp(argv[1], "b") == 0) { // generate random y0 uint8_t y0[HASH_BYTES]; generate_random_bytes(HASH_BYTES, y0); hash_str_t y0_str; sprint_hash_hex(y0, y0_str); printf("Random y0: %s\n", y0_str); printf("Starting cycle finding...\n"); uint64_t lambda, mu; brents_cycle_find_collision(HASH_BYTES, y0, hash_function, &lambda, &mu, m1, m2, brents_power_updated); printf("lambda: %" PRIu64 "\n", lambda); printf("mu: %" PRIu64 "\n", mu); } else if (strcmp(argv[1], "dp") == 0) { if (argc < 4) { printf("Usage: %s dp NUM_THREADS NUM_LEADING_ZEROS\n", argv[0]); return -1; } unsigned int num_threads = strtol(argv[2], NULL, 10); if (num_threads == 0) { printf("Usage: %s NUM_THREADS NUM_LEADING_ZEROS\n", argv[0]); return -1; } unsigned int num_leading_zeros = strtol(argv[3], NULL, 10); printf("Using %u leading zeros as dp-property!\n", num_leading_zeros); dp_find_collision_parallel(HASH_BYTES, hash_function, generate_random_bytes, num_threads, num_leading_zeros, m1, m2, dp_found_dp); } else if (strcmp(argv[1], "test") == 0) { // test iteration speed if (argc < 3) { printf("Expecting iteration parameter!\n"); return -1; } unsigned long num_iterations = strtoul(argv[2], NULL, 10); if (num_iterations == 0) { printf("Invalid number of iterations: %s\n", argv[2]); return -1; } printf("Running %lu hash iterations...\n", num_iterations); uint8_t y0[HASH_BYTES]; generate_random_bytes(HASH_BYTES, y0); for (unsigned long i = 0; i < num_iterations; ++i) { hash_function(y0, HASH_BYTES, y0); } } else { printf("Unknown method!\n"); return -1; } hash_t h1, h2; truncated_md5(m1, HASH_BYTES, h1); truncated_md5(m2, HASH_BYTES, h2); hash_str_t m1_str, m2_str, h1_str, h2_str; sprint_hash_hex(m1, m1_str); sprint_hash_hex(m2, m2_str); sprint_hash_hex(h1, h1_str); sprint_hash_hex(h2, h2_str); printf("m1: %s -> %s\n", m1_str, h1_str); printf("m2: %s -> %s\n", m2_str, h2_str); printf("Hamming distance: %u\n", hamming_distance_bytes(h1, h2, HASH_BYTES)); timespec_get(&end_time, TIME_UTC); printf("Computation took %ld seconds...\n", end_time.tv_sec - start_time.tv_sec); return 0; }