int sleeptest(int (*test)(struct timespec *, struct timespec *), bool subsec, bool sim_remain) { struct timespec tsa, tsb, tslp, tremain; int64_t delta1, delta2, delta3, round; sig = 0; signal(SIGALRM, sigalrm); if (subsec) { round = 1; delta3 = FUZZ; } else { round = 1000000000; delta3 = round; } tslp.tv_sec = delta3 / 1000000000; tslp.tv_nsec = delta3 % 1000000000; while (tslp.tv_sec <= MAXSLEEP) { /* * disturb sleep by signal on purpose */ if (tslp.tv_sec > ALARM && sig == 0) alarm(ALARM); clock_gettime(CLOCK_REALTIME, &tsa); (*test)(&tslp, &tremain); clock_gettime(CLOCK_REALTIME, &tsb); if (sim_remain) { timespecsub(&tsb, &tsa, &tremain); timespecsub(&tslp, &tremain, &tremain); } delta1 = (int64_t)tsb.tv_sec - (int64_t)tsa.tv_sec; delta1 *= BILLION; delta1 += (int64_t)tsb.tv_nsec - (int64_t)tsa.tv_nsec; delta2 = (int64_t)tremain.tv_sec * BILLION; delta2 += (int64_t)tremain.tv_nsec; delta3 = (int64_t)tslp.tv_sec * BILLION; delta3 += (int64_t)tslp.tv_nsec - delta1 - delta2; delta3 /= round; delta3 *= round; if (delta3 > FUZZ || delta3 < -FUZZ) { if (!sim_remain) atf_tc_expect_fail("Long reschedule latency " "due to PR kern/43997"); atf_tc_fail("Reschedule latency %"PRId64" exceeds " "allowable fuzz %lld", delta3, FUZZ); } delta3 = (int64_t)tslp.tv_sec * 2 * BILLION; delta3 += (int64_t)tslp.tv_nsec * 2; delta3 /= round; delta3 *= round; if (delta3 < FUZZ) break; tslp.tv_sec = delta3 / BILLION; tslp.tv_nsec = delta3 % BILLION; } ATF_REQUIRE_MSG(sig == 1, "Alarm did not fire!"); atf_tc_pass(); }
int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) { int bytes_read = -1; #if 0 int transferred; int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000); LOG("transferred: %d\n", transferred); return transferred; #endif pthread_mutex_lock(&dev->mutex); pthread_cleanup_push(&cleanup_mutex, dev); /* There's an input report queued up. Return it. */ if (dev->input_reports) { /* Return the first one */ bytes_read = return_data(dev, data, length); goto ret; } if (dev->shutdown_thread) { /* This means the device has been disconnected. An error code of -1 should be returned. */ bytes_read = -1; goto ret; } if (milliseconds == -1) { /* Blocking */ while (!dev->input_reports && !dev->shutdown_thread) { pthread_cond_wait(&dev->condition, &dev->mutex); } if (dev->input_reports) { bytes_read = return_data(dev, data, length); } } else if (milliseconds > 0) { /* Non-blocking, but called with timeout. */ int res; struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += milliseconds / 1000; ts.tv_nsec += (milliseconds % 1000) * 1000000; if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; } while (!dev->input_reports && !dev->shutdown_thread) { res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts); if (res == 0) { if (dev->input_reports) { bytes_read = return_data(dev, data, length); break; } /* If we're here, there was a spurious wake up or the read thread was shutdown. Run the loop again (ie: don't break). */ } else if (res == ETIMEDOUT) { /* Timed out. */ bytes_read = 0; break; } else { /* Error. */ bytes_read = -1; break; } } } else { /* Purely non-blocking */ bytes_read = 0; } ret: pthread_mutex_unlock(&dev->mutex); pthread_cleanup_pop(0); return bytes_read; }
int main(int argc, char *argv[]) { struct timespec timeBase, timeNow; long long delta, deltaPrevious; int sockfd, sockfdClient, buffLen, readLen, readIdx, count, port; struct sockaddr_in addrServ, addrClient; socklen_t addrClientLen; char buff[2], *buffLong, label[21]; clock_gettime(CLOCKTYPE, &timeBase); port = SERVER_PORT; if (2 <= argc) { port = atoi(argv[1]); if (0 >= port) { port = SERVER_PORT; } } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (0 > sockfd) { fprintf(stderr, "Error establishing socket.\n"); exit(1); } bzero((char *) &addrServ, sizeof(addrServ)); addrServ.sin_family = AF_INET; addrServ.sin_addr.s_addr = INADDR_ANY; addrServ.sin_port = htons(port); if (0 > bind(sockfd, (struct sockaddr *) &addrServ, sizeof(addrServ))) { fprintf(stderr, "Error binding socket to server port %d.\n", port); exit(1); } listen(sockfd, 5); printf("SERVER LISTENING ON PORT %d\n", port); fflush(stdout); // Enter loop accepting new connections for (count = 0;; count++) { addrClientLen = sizeof(addrClient); sockfdClient = accept(sockfd, (struct sockaddr *) &addrClient, &addrClientLen); if (0 > sockfdClient) { close(sockfd); fprintf(stderr, "Error accepting connection from port %d.\n", port); exit(1); } printf("NEW CONNECTION (%d)\n", count); fflush(stdout); deltaPrevious = -1; // Enter loop handling packets from this connection for (;;) { readLen = read(sockfdClient, buff, sizeof(buff)); if (0 == readLen) { break; } if (0 > readLen) { close(sockfdClient); close(sockfd); fprintf(stderr, "Error reading from connection on port %d.\n", port); exit(1); } #ifdef DEBUG printf("Read %d bytes\n", readLen); #endif buffLen = (unsigned int)buff[0] + 256 * (unsigned int)buff[1]; #ifdef DEBUG printf("Allocating %d bytes\n", buffLen); fflush(stdout); #endif buffLong = (char *) malloc((unsigned int)buffLen); if (NULL == buffLong) { close(sockfdClient); close(sockfd); fprintf(stderr, "Error allocating buffer for %d bytes.\n", buffLen); exit(1); } for (readIdx = 0; readIdx < buffLen; readIdx += readLen) { readLen = read(sockfdClient, buffLong + readIdx, buffLen - readIdx); if (0 == readLen) { break; } else if (0 > readLen) { close(sockfdClient); close(sockfd); fprintf(stderr, "Error reading from connection on port %d.\n", port); exit(1); } } if (0 == readLen) { break; } if (readIdx > sizeof(label) - 1) { readIdx = sizeof(label) - 1; } strncpy(label, buffLong, readIdx); label[readIdx] = 0; clock_gettime(CLOCKTYPE, &timeNow); delta = timespecDiff(&timeNow, &timeBase); if (-1 == deltaPrevious) { printf(":%d:%ld::%s:\n", count, (long)(delta / 1000000), label); } else { printf(":%d:%ld:%ld:%s:\n", count, (long)(delta / 1000000), (long)((delta - deltaPrevious) / 1000000), label); } fflush(stdout); deltaPrevious = delta; free(buffLong); } close(sockfdClient); printf("CONNECTION CLOSED (%d)\n", count); fflush(stdout); } close(sockfd); return 0; }
static PyObject * py_get_time(PyObject *self, PyObject *args) { struct timespec first; clock_gettime(CLOCK_MONOTONIC, &first); return Py_BuildValue("(ll)", first.tv_sec, first.tv_nsec); }
static void monotime(struct timeval *tv) { struct timespec ts; clock_gettime(CLOCK_BOOTTIME, &ts); TIMESPEC_TO_TIMEVAL(tv, &ts); }
bool CanPump::pump() { if(!_can_initialized) { std::cout << "WARNING: Attempting to pump the CanPump before the CAN " << "communication has been initialized!" << std::endl; return false; } if(_can_error) return false; if(_first_tick) { if(clock_gettime(CLOCK_MONOTONIC, &_deadline) != 0) { std::cout << "ERROR: clock_gettime triggered error '" << strerror(errno) << "' (" << errno << ")" << std::endl; return false; } _first_tick = false; } increment_clock(_deadline, _timestep); timespec_t time; clock_gettime(CLOCK_MONOTONIC, &time); double diff = clock_diff(_deadline, time); if(fabs(_timestep-diff) > period_threshold) { std::cout << "WARNING: CanPump is off schedule by " << _timestep-diff << " seconds" << std::endl; } int expectation = _get_max_frame_expectation(); if(expectation * can_frame_bit_size > _bitrate * diff) { std::cout << "WARNING: Expected size of CAN frame transfer (" << expectation*can_frame_bit_size << ") exceeds the bitrate setting (" << _bitrate * diff << ")\n" << " -- This may result in frames being dropped!" << std::endl; if( diff < 0 ) { std::cout << "Skipping this cycle" << std::endl; return true; } } for(size_t i=0; i<_devices.size(); ++i) { _devices[i]->update(); } if(_get_max_frame_count() > 0) { double frame_dt = diff/(double)(_get_max_frame_count()); while(clock_diff(_deadline, time) > 0) { _send_next_frames(); if(_can_error) return false; increment_clock(time, frame_dt); _wait_on_next_frames(time); if(_can_error) return false; } } else { _wait_on_next_frames(_deadline); } for(size_t i=0; i<_channels.size(); ++i) { _channels[i].reset_counter(); } return true; }
static uint64_t get_time() { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec*(uint64_t)1000000000 + t.tv_nsec; }
int Module_Tick::setUp(IBus *bus) { clock_gettime(CLOCK_REALTIME, &lastTick); bus->in(MSG_TICK, nullptr, nullptr); return 0; }
/** * Handles all the video streaming and saving of the image shots * This is a sepereate thread, so it needs to be thread safe! */ static void *video_thread_function(void *data) { struct video_config_t *vid = (struct video_config_t *)&(VIDEO_THREAD_CAMERA); struct image_t img_jpeg; struct image_t img_color; // create the images if (vid->filters) { // fixme: don't hardcode size, works for bebop front camera for now #define IMG_FLT_SIZE 272 image_create(&img_color, IMG_FLT_SIZE, IMG_FLT_SIZE, IMAGE_YUV422); image_create(&img_jpeg, IMG_FLT_SIZE, IMG_FLT_SIZE, IMAGE_JPEG); } else { image_create(&img_jpeg, vid->w, vid->h, IMAGE_JPEG); } // Start the streaming of the V4L2 device if (!v4l2_start_capture(video_thread.dev)) { printf("[video_thread-thread] Could not start capture of %s.\n", video_thread.dev->name); return 0; } // be nice to the more important stuff set_nice_level(10); // Initialize timing struct timespec time_now; struct timespec time_prev; clock_gettime(CLOCK_MONOTONIC, &time_prev); // Start streaming video_thread.is_running = true; while (video_thread.is_running) { // get time in us since last run clock_gettime(CLOCK_MONOTONIC, &time_now); unsigned int dt_us = sys_time_elapsed_us(&time_prev, &time_now); time_prev = time_now; // sleep remaining time to limit to specified fps uint32_t fps_period_us = (uint32_t)(1000000. / (float)video_thread.fps); if (dt_us < fps_period_us) { usleep(fps_period_us - dt_us); } else { fprintf(stderr, "video_thread: desired %i fps, only managing %.1f fps\n", video_thread.fps, 1000000.f / dt_us); } // Wait for a new frame (blocking) struct image_t img; v4l2_image_get(video_thread.dev, &img); // pointer to the final image to pass for saving and further processing struct image_t *img_final = &img; // run selected filters if (vid->filters) { if (vid->filters & VIDEO_FILTER_DEBAYER) { BayerToYUV(&img, &img_color, 0, 0); } // use color image for further processing img_final = &img_color; } // Check if we need to take a shot if (video_thread.take_shot) { video_thread_save_shot(img_final, &img_jpeg); video_thread.take_shot = false; } // Run processing if required cv_run(img_final); // Free the image v4l2_image_free(video_thread.dev, &img); } image_free(&img_jpeg); image_free(&img_color); return 0; }
/* * Initialize the stack. The connection manager functions, upper layer * receive functions are mandatory. */ int sip_stack_init(sip_stack_init_t *stack_val) { #ifdef __linux__ struct timespec tspec; #endif /* * If the stack has already been configured, return error */ if (sip_stack_send != NULL || stack_val->sip_version != SIP_STACK_VERSION) { return (EINVAL); } if (stack_val->sip_io_pointers == NULL || stack_val->sip_ulp_pointers == NULL) { return (EINVAL); } sip_ulp_recv = stack_val->sip_ulp_pointers->sip_ulp_recv; sip_manage_dialog = stack_val->sip_stack_flags & SIP_STACK_DIALOGS; sip_stack_send = stack_val->sip_io_pointers->sip_conn_send; sip_refhold_conn = stack_val->sip_io_pointers->sip_hold_conn_object; sip_refrele_conn = stack_val->sip_io_pointers->sip_rel_conn_object; sip_is_conn_stream = stack_val->sip_io_pointers->sip_conn_is_stream; sip_is_conn_reliable = stack_val->sip_io_pointers->sip_conn_is_reliable; sip_conn_rem_addr = stack_val->sip_io_pointers->sip_conn_remote_address; sip_conn_local_addr = stack_val->sip_io_pointers->sip_conn_local_address; sip_conn_transport = stack_val->sip_io_pointers->sip_conn_transport; sip_header_function_table_external = stack_val->sip_function_table; if (sip_ulp_recv == NULL || sip_stack_send == NULL || sip_refhold_conn == NULL || sip_refrele_conn == NULL || sip_is_conn_stream == NULL || sip_is_conn_reliable == NULL || sip_conn_rem_addr == NULL || sip_conn_local_addr == NULL || sip_conn_transport == NULL) { err_ret: sip_ulp_recv = NULL; sip_stack_send = NULL; sip_refhold_conn = NULL; sip_refrele_conn = NULL; sip_is_conn_stream = NULL; sip_is_conn_reliable = NULL; sip_conn_rem_addr = NULL; sip_conn_local_addr = NULL; sip_conn_transport = NULL; sip_header_function_table_external = NULL; sip_stack_timeout = NULL; sip_stack_untimeout = NULL; return (EINVAL); } sip_conn_timer1 = stack_val->sip_io_pointers->sip_conn_timer1; sip_conn_timer2 = stack_val->sip_io_pointers->sip_conn_timer2; sip_conn_timer4 = stack_val->sip_io_pointers->sip_conn_timer4; sip_conn_timerd = stack_val->sip_io_pointers->sip_conn_timerd; /* * Use Appln timeout routines, if provided */ if (stack_val->sip_ulp_pointers->sip_ulp_timeout != NULL) { if (stack_val->sip_ulp_pointers->sip_ulp_untimeout == NULL) goto err_ret; sip_stack_timeout = stack_val->sip_ulp_pointers->sip_ulp_timeout; sip_stack_untimeout = stack_val->sip_ulp_pointers->sip_ulp_untimeout; } else { if (stack_val->sip_ulp_pointers->sip_ulp_untimeout != NULL) goto err_ret; sip_timeout_init(); sip_stack_timeout = sip_timeout; sip_stack_untimeout = sip_untimeout; } /* * Manage Dialogs? */ if (sip_manage_dialog) { sip_dialog_init(stack_val->sip_ulp_pointers->sip_ulp_dlg_del, stack_val->sip_ulp_pointers->sip_ulp_dlg_state_cb); } sip_xaction_init(stack_val->sip_ulp_pointers->sip_ulp_trans_error, stack_val->sip_ulp_pointers->sip_ulp_trans_state_cb); /* * Initialize SIP traffic counter mutex */ (void) pthread_mutex_init(&sip_counters.sip_counter_mutex, NULL); /* * Initialize SIP logfile structures mutex */ (void) pthread_mutex_init(&trans_log.sip_logfile_mutex, NULL); (void) pthread_mutex_init(&dialog_log.sip_logfile_mutex, NULL); #ifdef __linux__ if (clock_gettime(CLOCK_REALTIME, &tspec) != 0) goto err_ret; sip_hash_salt = tspec.tv_nsec; #else sip_hash_salt = gethrtime(); #endif (void) pthread_mutex_init(&sip_sent_by_lock, NULL); return (0); }
static int __write_to_log_daemon(log_id_t log_id, struct iovec *vec, size_t nr) { ssize_t ret; #if FAKE_LOG_DEVICE int log_fd; if (/*(int)log_id >= 0 &&*/ (int)log_id < (int)LOG_ID_MAX) { log_fd = log_fds[(int)log_id]; } else { return -EBADF; } do { ret = fakeLogWritev(log_fd, vec, nr); if (ret < 0) { ret = -errno; } } while (ret == -EINTR); #else static const unsigned header_length = 2; struct iovec newVec[nr + header_length]; android_log_header_t header; android_pmsg_log_header_t pmsg_header; struct timespec ts; size_t i, payload_size; static uid_t last_uid = AID_ROOT; /* logd *always* starts up as AID_ROOT */ static pid_t last_pid = (pid_t) -1; static atomic_int_fast32_t dropped; if (!nr) { return -EINVAL; } if (last_uid == AID_ROOT) { /* have we called to get the UID yet? */ last_uid = getuid(); } if (last_pid == (pid_t) -1) { last_pid = getpid(); } /* * struct { * // what we provide to pstore * android_pmsg_log_header_t pmsg_header; * // what we provide to socket * android_log_header_t header; * // caller provides * union { * struct { * char prio; * char payload[]; * } string; * struct { * uint32_t tag * char payload[]; * } binary; * }; * }; */ clock_gettime(CLOCK_REALTIME, &ts); pmsg_header.magic = LOGGER_MAGIC; pmsg_header.len = sizeof(pmsg_header) + sizeof(header); pmsg_header.uid = last_uid; pmsg_header.pid = last_pid; header.tid = gettid(); header.realtime.tv_sec = ts.tv_sec; header.realtime.tv_nsec = ts.tv_nsec; newVec[0].iov_base = (unsigned char *) &pmsg_header; newVec[0].iov_len = sizeof(pmsg_header); newVec[1].iov_base = (unsigned char *) &header; newVec[1].iov_len = sizeof(header); if (logd_fd > 0) { int32_t snapshot = atomic_exchange_explicit(&dropped, 0, memory_order_relaxed); if (snapshot) { android_log_event_int_t buffer; header.id = LOG_ID_EVENTS; buffer.header.tag = htole32(LIBLOG_LOG_TAG); buffer.payload.type = EVENT_TYPE_INT; buffer.payload.data = htole32(snapshot); newVec[2].iov_base = &buffer; newVec[2].iov_len = sizeof(buffer); ret = TEMP_FAILURE_RETRY(writev(logd_fd, newVec + 1, 2)); if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) { atomic_fetch_add_explicit(&dropped, snapshot, memory_order_relaxed); } } } header.id = log_id; for (payload_size = 0, i = header_length; i < nr + header_length; i++) { newVec[i].iov_base = vec[i - header_length].iov_base; payload_size += newVec[i].iov_len = vec[i - header_length].iov_len; if (payload_size > LOGGER_ENTRY_MAX_PAYLOAD) { newVec[i].iov_len -= payload_size - LOGGER_ENTRY_MAX_PAYLOAD; if (newVec[i].iov_len) { ++i; } payload_size = LOGGER_ENTRY_MAX_PAYLOAD; break; } } pmsg_header.len += payload_size; if (pstore_fd >= 0) { TEMP_FAILURE_RETRY(writev(pstore_fd, newVec, i)); } if (last_uid == AID_LOGD) { /* logd, after initialization and priv drop */ /* * ignore log messages we send to ourself (logd). * Such log messages are often generated by libraries we depend on * which use standard Android logging. */ return 0; } if (logd_fd < 0) { return -EBADF; } /* * The write below could be lost, but will never block. * * To logd, we drop the pmsg_header * * ENOTCONN occurs if logd dies. * EAGAIN occurs if logd is overloaded. */ ret = TEMP_FAILURE_RETRY(writev(logd_fd, newVec + 1, i - 1)); if (ret < 0) { ret = -errno; if (ret == -ENOTCONN) { #if !defined(_WIN32) pthread_mutex_lock(&log_init_lock); #endif close(logd_fd); logd_fd = -1; ret = __write_to_log_initialize(); #if !defined(_WIN32) pthread_mutex_unlock(&log_init_lock); #endif if (ret < 0) { return ret; } ret = TEMP_FAILURE_RETRY(writev(logd_fd, newVec + 1, i - 1)); if (ret < 0) { ret = -errno; } } } if (ret > (ssize_t)sizeof(header)) { ret -= sizeof(header); } else if (ret == -EAGAIN) { atomic_fetch_add_explicit(&dropped, 1, memory_order_relaxed); } #endif return ret; }
int main(int argc, char *argv[]) { struct ptp_clock_caps caps; struct ptp_extts_event event; struct ptp_extts_request extts_request; struct ptp_perout_request perout_request; struct ptp_pin_desc desc; struct timespec ts; struct timex tx; static timer_t timerid; struct itimerspec timeout; struct sigevent sigevent; struct ptp_clock_time *pct; struct ptp_sys_offset *sysoff; char *progname; int i, c, cnt, fd; char *device = DEVICE; clockid_t clkid; int adjfreq = 0x7fffffff; int adjtime = 0; int capabilities = 0; int extts = 0; int gettime = 0; int index = 0; int list_pins = 0; int oneshot = 0; int pct_offset = 0; int n_samples = 0; int periodic = 0; int perout = -1; int pin_index = -1, pin_func; int pps = -1; int seconds = 0; int settime = 0; int64_t t1, t2, tp; int64_t interval, offset; progname = strrchr(argv[0], '/'); progname = progname ? 1+progname : argv[0]; while (EOF != (c = getopt(argc, argv, "a:A:cd:e:f:ghi:k:lL:p:P:sSt:T:v"))) { switch (c) { case 'a': oneshot = atoi(optarg); break; case 'A': periodic = atoi(optarg); break; case 'c': capabilities = 1; break; case 'd': device = optarg; break; case 'e': extts = atoi(optarg); break; case 'f': adjfreq = atoi(optarg); break; case 'g': gettime = 1; break; case 'i': index = atoi(optarg); break; case 'k': pct_offset = 1; n_samples = atoi(optarg); break; case 'l': list_pins = 1; break; case 'L': cnt = sscanf(optarg, "%d,%d", &pin_index, &pin_func); if (cnt != 2) { usage(progname); return -1; } break; case 'p': perout = atoi(optarg); break; case 'P': pps = atoi(optarg); break; case 's': settime = 1; break; case 'S': settime = 2; break; case 't': adjtime = atoi(optarg); break; case 'T': settime = 3; seconds = atoi(optarg); break; case 'h': usage(progname); return 0; case '?': default: usage(progname); return -1; } } fd = open(device, O_RDWR); if (fd < 0) { fprintf(stderr, "opening %s: %s\n", device, strerror(errno)); return -1; } clkid = get_clockid(fd); if (CLOCK_INVALID == clkid) { fprintf(stderr, "failed to read clock id\n"); return -1; } if (capabilities) { if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) { perror("PTP_CLOCK_GETCAPS"); } else { printf("capabilities:\n" " %d maximum frequency adjustment (ppb)\n" " %d programmable alarms\n" " %d external time stamp channels\n" " %d programmable periodic signals\n" " %d pulse per second\n" " %d programmable pins\n", caps.max_adj, caps.n_alarm, caps.n_ext_ts, caps.n_per_out, caps.pps, caps.n_pins); } } if (0x7fffffff != adjfreq) { memset(&tx, 0, sizeof(tx)); tx.modes = ADJ_FREQUENCY; tx.freq = ppb_to_scaled_ppm(adjfreq); if (clock_adjtime(clkid, &tx)) { perror("clock_adjtime"); } else { puts("frequency adjustment okay"); } } if (adjtime) { memset(&tx, 0, sizeof(tx)); tx.modes = ADJ_SETOFFSET; tx.time.tv_sec = adjtime; tx.time.tv_usec = 0; if (clock_adjtime(clkid, &tx) < 0) { perror("clock_adjtime"); } else { puts("time shift okay"); } } if (gettime) { if (clock_gettime(clkid, &ts)) { perror("clock_gettime"); } else { printf("clock time: %ld.%09ld or %s", ts.tv_sec, ts.tv_nsec, ctime(&ts.tv_sec)); } } if (settime == 1) { clock_gettime(CLOCK_REALTIME, &ts); if (clock_settime(clkid, &ts)) { perror("clock_settime"); } else { puts("set time okay"); } } if (settime == 2) { clock_gettime(clkid, &ts); if (clock_settime(CLOCK_REALTIME, &ts)) { perror("clock_settime"); } else { puts("set time okay"); } } if (settime == 3) { ts.tv_sec = seconds; ts.tv_nsec = 0; if (clock_settime(clkid, &ts)) { perror("clock_settime"); } else { puts("set time okay"); } } if (extts) { memset(&extts_request, 0, sizeof(extts_request)); extts_request.index = index; extts_request.flags = PTP_ENABLE_FEATURE; if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) { perror("PTP_EXTTS_REQUEST"); extts = 0; } else { puts("external time stamp request okay"); } for (; extts; extts--) { cnt = read(fd, &event, sizeof(event)); if (cnt != sizeof(event)) { perror("read"); break; } printf("event index %u at %lld.%09u\n", event.index, event.t.sec, event.t.nsec); fflush(stdout); } /* Disable the feature again. */ extts_request.flags = 0; if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) { perror("PTP_EXTTS_REQUEST"); } } if (list_pins) { int n_pins = 0; if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) { perror("PTP_CLOCK_GETCAPS"); } else { n_pins = caps.n_pins; } for (i = 0; i < n_pins; i++) { desc.index = i; if (ioctl(fd, PTP_PIN_GETFUNC, &desc)) { perror("PTP_PIN_GETFUNC"); break; } printf("name %s index %u func %u chan %u\n", desc.name, desc.index, desc.func, desc.chan); } } if (oneshot) { install_handler(SIGALRM, handle_alarm); /* Create a timer. */ sigevent.sigev_notify = SIGEV_SIGNAL; sigevent.sigev_signo = SIGALRM; if (timer_create(clkid, &sigevent, &timerid)) { perror("timer_create"); return -1; } /* Start the timer. */ memset(&timeout, 0, sizeof(timeout)); timeout.it_value.tv_sec = oneshot; if (timer_settime(timerid, 0, &timeout, NULL)) { perror("timer_settime"); return -1; } pause(); timer_delete(timerid); } if (periodic) { install_handler(SIGALRM, handle_alarm); /* Create a timer. */ sigevent.sigev_notify = SIGEV_SIGNAL; sigevent.sigev_signo = SIGALRM; if (timer_create(clkid, &sigevent, &timerid)) { perror("timer_create"); return -1; } /* Start the timer. */ memset(&timeout, 0, sizeof(timeout)); timeout.it_interval.tv_sec = periodic; timeout.it_value.tv_sec = periodic; if (timer_settime(timerid, 0, &timeout, NULL)) { perror("timer_settime"); return -1; } while (1) { pause(); } timer_delete(timerid); } if (perout >= 0) { if (clock_gettime(clkid, &ts)) { perror("clock_gettime"); return -1; } memset(&perout_request, 0, sizeof(perout_request)); perout_request.index = index; perout_request.start.sec = ts.tv_sec + 2; perout_request.start.nsec = 0; perout_request.period.sec = 0; perout_request.period.nsec = perout; if (ioctl(fd, PTP_PEROUT_REQUEST, &perout_request)) { perror("PTP_PEROUT_REQUEST"); } else { puts("periodic output request okay"); } } if (pin_index >= 0) { memset(&desc, 0, sizeof(desc)); desc.index = pin_index; desc.func = pin_func; desc.chan = index; if (ioctl(fd, PTP_PIN_SETFUNC, &desc)) { perror("PTP_PIN_SETFUNC"); } else { puts("set pin function okay"); } } if (pps != -1) { int enable = pps ? 1 : 0; if (ioctl(fd, PTP_ENABLE_PPS, enable)) { perror("PTP_ENABLE_PPS"); } else { puts("pps for system time request okay"); } } if (pct_offset) { if (n_samples <= 0 || n_samples > 25) { puts("n_samples should be between 1 and 25"); usage(progname); return -1; } sysoff = calloc(1, sizeof(*sysoff)); if (!sysoff) { perror("calloc"); return -1; } sysoff->n_samples = n_samples; if (ioctl(fd, PTP_SYS_OFFSET, sysoff)) perror("PTP_SYS_OFFSET"); else puts("system and phc clock time offset request okay"); pct = &sysoff->ts[0]; for (i = 0; i < sysoff->n_samples; i++) { t1 = pctns(pct+2*i); tp = pctns(pct+2*i+1); t2 = pctns(pct+2*i+2); interval = t2 - t1; offset = (t2 + t1) / 2 - tp; printf("system time: %" PRId64 ".%u\n", (pct+2*i)->sec, (pct+2*i)->nsec); printf("phc time: %" PRId64 ".%u\n", (pct+2*i+1)->sec, (pct+2*i+1)->nsec); printf("system time: %" PRId64 ".%u\n", (pct+2*i+2)->sec, (pct+2*i+2)->nsec); printf("system/phc clock time offset is %" PRId64 " ns\n" "system clock time delay is %" PRId64 " ns\n", offset, interval); } free(sysoff); } close(fd); return 0; }
int main(int argc, char *argv[]) { struct sigevent ev; struct sigaction act; struct timespec tpT0, tpclock; struct itimerspec its; timer_t tid; int flags = 0; /* * set up sigevent for timer * set up sigaction to catch signal */ ev.sigev_notify = SIGEV_SIGNAL; ev.sigev_signo = SIGTOTEST; act.sa_handler=handler; act.sa_flags=0; if (sigemptyset(&act.sa_mask) != 0) { perror("sigemptyset() was not successful\n"); return PTS_UNRESOLVED; } if (sigaction(SIGTOTEST, &act, 0) != 0) { perror("sigaction() was not successful\n"); return PTS_UNRESOLVED; } if (clock_gettime(CLOCK_REALTIME, &tpT0) != 0) { perror("clock_gettime() was not successful\n"); return PTS_UNRESOLVED; } if (timer_create(CLOCK_REALTIME, &ev, &tid) != 0) { perror("timer_create() did not return success\n"); return PTS_UNRESOLVED; } flags |= TIMER_ABSTIME; its.it_interval.tv_sec = 0; its.it_interval.tv_nsec = 0; its.it_value.tv_sec = tpT0.tv_sec + TIMEROFFSET; its.it_value.tv_nsec = tpT0.tv_nsec; if (timer_settime(tid, flags, &its, NULL) != 0) { perror("timer_settime() did not return success\n"); return PTS_UNRESOLVED; } tpclock.tv_sec = its.it_value.tv_sec + CLOCKOFFSET; tpclock.tv_nsec = its.it_value.tv_nsec; getBeforeTime(&tpreset); if (clock_settime(CLOCK_REALTIME, &tpclock) != 0) { printf("clock_settime() was not successful\n"); return PTS_UNRESOLVED; } sleep(SHORTTIME); printf("timer should have expired _immediately_\n"); tpreset.tv_sec += SHORTTIME; setBackTime(tpreset); return PTS_FAIL; }
int main (void) { struct timespec ts; timer_t timer_sig, timer_thr1, timer_thr2; int retval; struct sigevent sigev1 = { .sigev_notify = SIGEV_SIGNAL, .sigev_signo = ZSIGALRM }; struct sigevent sigev2 = { .sigev_notify = SIGEV_THREAD, ._sigev_un = { ._sigev_thread = { ._function = notify_func } } }; struct itimerspec itimer1 = { { 0, 200000000 }, { 0, 200000000 } }; struct itimerspec itimer2 = { { 0, 100000000 }, { 0, 500000000 } }; struct itimerspec itimer3 = { { 0, 150000000 }, { 0, 300000000 } }; struct itimerspec old; retval = clock_gettime (CLOCK_REALTIME, &ts); setvbuf (stdout, 0, _IOLBF, 0); printf ("clock_gettime returned %d, timespec = { %ld, %ld }\n", retval, ts.tv_sec, ts.tv_nsec); retval = clock_getres (CLOCK_REALTIME, &ts); printf ("clock_getres returned %d, timespec = { %ld, %ld }\n", retval, ts.tv_sec, ts.tv_nsec); timer_create (CLOCK_REALTIME, &sigev1, &timer_sig); timer_create (CLOCK_REALTIME, &sigev2, &timer_thr1); timer_create (CLOCK_REALTIME, &sigev2, &timer_thr2); timer_settime (timer_thr1, 0, &itimer2, &old); timer_settime (timer_thr2, 0, &itimer3, &old); signal (ZSIGALRM, signal_func); timer_settime (timer_sig, 0, &itimer1, &old); timer_delete (-1); intr_sleep (3); timer_delete (timer_sig); timer_delete (timer_thr1); intr_sleep (3); timer_delete (timer_thr2); return 0; }
//Function to read in audio data from speaker through audio input pin on the audio cape void readAudioData(int mArraySize, char mArray[]) { struct timespec currentTime; struct timespec lastChange; char cur; char prev; int curPos = 0; int bitsRead = 0; int numOfPeriods; int i; uint64_t timeDifferenceNS; uint64_t audioPeriod; uint64_t difference; //Reads in different numbers for period between bits read from Audio Cape in different states if (state == 1) { audioPeriod = RECORDING_PERIOD_NS; difference = RECORDING_PERIOD_DIFFERENCE; } else { audioPeriod = TUNER_PERIOD_NS; difference = TUNER_PERIOD_DIFFERENCE; } // Check initial reading of Audio Input pin if (is_high(9, 25)) { cur = 1; mArray[curPos] = 1; prev = 1; } else { cur = 0; mArray[curPos] = 0; prev = 0; } ++curPos; ++bitsRead; clock_gettime(CLOCK_REALTIME, ¤tTime); lastChange = currentTime; // Loops that continuosly poll the audio input pin and modifies the char array as needed while (curPos < mArraySize - 1 && (state == 1 && stopButton == 0)) { // Check current input from audio input pin if (is_high(9, 25)) { cur = 1; } else { cur = 0; } // Check to see if whether there has been a change of input from audio input pin if (cur != prev) { // Calculate time difference between changes of input from audio input pin clock_gettime(CLOCK_REALTIME, ¤tTime); if (currentTime.tv_nsec < lastChange.tv_nsec) { timeDifferenceNS = ((1000000000) * (currentTime.tv_sec - 1 - lastChange.tv_sec)) + ((1000000000 + currentTime.tv_nsec) - lastChange.tv_nsec); } else { timeDifferenceNS = ((1000000000) * (currentTime.tv_sec - lastChange.tv_sec)) + (currentTime.tv_nsec - lastChange.tv_nsec); } numOfPeriods = timeDifferenceNS / AUDIOCAPE_PERIOD_NS; // Modify character array as needed to store input from audio pin for (i = 0; (i < numOfPeriods) && (bitsRead < BIT_DEPTH); ++i) { mArray[curPos] = cur; ++curPos; ++bitsRead; } prev = cur; // Reset the bitsRead variable if (bitsRead > BIT_DEPTH) { bitsRead = 0; // If there is a difference between sampling rate of Audio Cape and current sampling rate, sleep if (difference != 0) { currentTime.tv_nsec += difference; clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, ¤tTime, NULL); } } } } // If input has finished, end array with an 'f' char and fill remaining chars as literal 0 mArray[curPos] = 'f'; for (i = curPos + 1; i < mArraySize - 1; ++i) { mArray[i] = 0; } }
static timestamp_t current_timestamp(void) { struct timespec ts; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); return ((uint64_t)(ts.tv_sec)) * 1000000000ULL + ts.tv_nsec; }
static void mainloop(void) { gtimer_t *gti; gti_callback_t *cb; struct timespec ts; while(tvheadend_running) { clock_gettime(CLOCK_REALTIME, &ts); /* 1sec stuff */ if (ts.tv_sec > dispatch_clock) { dispatch_clock = ts.tv_sec; spawn_reaper(); /* reap spawned processes */ comet_flush(); /* Flush idle comet mailboxes */ } /* Global timers */ pthread_mutex_lock(&global_lock); // TODO: there is a risk that if timers re-insert themselves to // the top of the list with a 0 offset we could loop indefinitely #if 0 tvhdebug("gtimer", "now %ld.%09ld", ts.tv_sec, ts.tv_nsec); LIST_FOREACH(gti, >imers, gti_link) tvhdebug("gtimer", " gti %p expire %ld.%08ld", gti, gti->gti_expire.tv_sec, gti->gti_expire.tv_nsec); #endif while((gti = LIST_FIRST(>imers)) != NULL) { if ((gti->gti_expire.tv_sec > ts.tv_sec) || ((gti->gti_expire.tv_sec == ts.tv_sec) && (gti->gti_expire.tv_nsec > ts.tv_nsec))) { ts = gti->gti_expire; break; } cb = gti->gti_callback; //tvhdebug("gtimer", "%p callback", gti); LIST_REMOVE(gti, gti_link); gti->gti_callback = NULL; cb(gti->gti_opaque); } /* Bound wait */ if ((LIST_FIRST(>imers) == NULL) || (ts.tv_sec > (dispatch_clock + 1))) { ts.tv_sec = dispatch_clock + 1; ts.tv_nsec = 0; } /* Wait */ //tvhdebug("gtimer", "wait till %ld.%09ld", ts.tv_sec, ts.tv_nsec); pthread_cond_timedwait(>imer_cond, &global_lock, &ts); pthread_mutex_unlock(&global_lock); } }
void go(SGLVData *data, int nbiter){ int i; mpz_t k_rd, ZZ, tmp; mpz_inits (k_rd, ZZ, tmp, NULL); gmp_randstate_t rand_gen; unsigned long seed = time(NULL); gmp_randinit_default(rand_gen); gmp_randseed_ui(rand_gen, seed); SGLVScalar k; JacPoint jp; struct timespec start1,start2; struct timespec end1,end2; uint64_t diff1,diff2, diff3; printf("\nSGLV 256 bits benchmark, running...\n\n"); diff1 = 0; diff2 = 0; init_jacPoint(&jp); for (i = 0; i < nbiter; i++) { mpz_urandomb (k_rd, rand_gen, BIT_SIZE); mpz_mod (k_rd, k_rd, data->efp); apply_endo(((data->PP)+1), (data->PP), beta); /* Point PHI_P */ add_aff_aff(((data->PP)+1), (data->PP)); /* Point P+PHI_P */ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start1); init_glvScalar(&k); build_glvScalar(&k, k_rd, data->aa, data->bb, data->Na); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end1); diff1 += BILLION * (end1.tv_sec - start1.tv_sec) + end1.tv_nsec - start1.tv_nsec; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start1); point_from_SGLVScalar(&jp, &k, data->PP); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end1); diff2 += BILLION * (end1.tv_sec - start1.tv_sec) + end1.tv_nsec - start1.tv_nsec; mpz_invert (ZZ, jp.Z, p); mpz_mul (tmp, ZZ, ZZ); // tmp = ZZ^2 //~ P is transformed in affine coordinates for next iteration mpz_mul (data->PP[0].X, jp.X, tmp); mpz_mod (data->PP[0].X, data->PP[0].X, p); mpz_mul (data->PP[0].Y, jp.Y, tmp); mpz_mul (data->PP[0].Y, data->PP[0].Y, ZZ); mpz_mod (data->PP[0].Y, data->PP[0].Y, p); } diff3 = diff1 + diff2; if (is_on_curve_jac(&jp, ca, cb)){ printf("\nMULT: kP OK\n"); print_jacPoint(&jp); printf("Elapsed time = %llu %llu %llu nanoseconds\n", (long long unsigned int) diff1, (long long unsigned int) diff2, (long long unsigned int) diff3); } else printf("MULT: kP non OK\n"); mpz_clears (k_rd, ZZ, tmp, NULL); free_jacPoint(&jp); gmp_randclear(rand_gen); }
void Timer::restart() { if (-1 == clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &m_implementation->start_time)) throw Common::NotSupported(FromHere(), "Couldn't initialize high resolution timer"); }
int main(int argc, char *argv[]) { struct timespec tssleep, tsbefore, tsafter, tsremain; int pid; struct sigaction act; if (clock_gettime(CLOCK_REALTIME, &tsbefore) != 0) { perror("clock_gettime() did not return success\n"); return PTS_UNRESOLVED; } if ((pid = fork()) == 0) { /* child here */ int sleptplusremaining; act.sa_handler=handler; act.sa_flags=0; if (sigemptyset(&act.sa_mask) != 0) { perror("sigemptyset() did not return success\n"); return CHILDFAIL; } if (sigaction(SIGABRT, &act, 0) != 0) { perror("sigaction() did not return success\n"); return CHILDFAIL; } tssleep.tv_sec=SLEEPSEC; tssleep.tv_nsec=0; if (clock_nanosleep(CLOCK_REALTIME, 0, &tssleep, &tsremain) == EINTR) { if (clock_gettime(CLOCK_REALTIME, &tsafter) != 0) { perror("clock_gettime() failed\n"); return CHILDFAIL; } sleptplusremaining = (tsafter.tv_sec-tsbefore.tv_sec) + tsremain.tv_sec; if (abs(sleptplusremaining - SLEEPSEC) <= OKDELTA) { printf("PASS - within %d difference\n", abs(sleptplusremaining - SLEEPSEC)); return CHILDPASS; } else { printf("FAIL - within %d difference\n", abs(sleptplusremaining - SLEEPSEC)); return CHILDFAIL; } return CHILDFAIL; } else { printf("clock_nanosleep() did not return EINTR\n"); return CHILDFAIL; } } else { /* parent here */ int i; sleep(1); if (kill(pid, SIGABRT) != 0) { printf("Could not raise signal being tested\n"); return PTS_UNRESOLVED; } if (wait(&i) == -1) { perror("Error waiting for child to exit\n"); return PTS_UNRESOLVED; } if (WIFEXITED(i) && WEXITSTATUS(i)) { printf("Child exited normally\n"); printf("Test PASSED\n"); return PTS_PASS; } else { printf("Child did not exit normally.\n"); printf("Test FAILED\n"); return PTS_FAIL; } } return PTS_UNRESOLVED; }
float now_ms() { struct timespec res; clock_gettime( CLOCK_REALTIME, &res ); return 1000.0 * res.tv_sec + ( float ) res.tv_nsec / 1e6; }
timespec getTime() { timespec now; clock_gettime(CLOCK_REALTIME,&now); return now; }