You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

common.c 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "common.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. struct timespec get_time(void)
  6. {
  7. struct timespec start_time;
  8. clock_gettime(CLOCK_MONOTONIC, &start_time);
  9. return start_time;
  10. }
  11. struct timespec time_diff(struct timespec* ts1, struct timespec* ts2)
  12. {
  13. static struct timespec ts;
  14. ts.tv_sec = ts1->tv_sec - ts2->tv_sec;
  15. ts.tv_nsec = ts1->tv_nsec - ts2->tv_nsec;
  16. if (ts.tv_nsec < 0) {
  17. ts.tv_sec--;
  18. ts.tv_nsec += 1000000000;
  19. }
  20. return ts;
  21. }
  22. struct timespec get_duration(struct timespec* ts)
  23. {
  24. struct timespec time = get_time();
  25. return time_diff(&time, ts);
  26. }
  27. void print_time(struct timespec* ts)
  28. {
  29. long ns = ts->tv_nsec % 1000;
  30. long us = (ts->tv_nsec / 1000) % 1000;
  31. long ms = (ts->tv_nsec / 1000000) % 1000;
  32. long s = (ts->tv_nsec / 1000000000) % 1000 + ts->tv_sec;
  33. long t = (s * 1000000000) + (ms * 1000000) + (us * 1000) + ns;
  34. printf("%3lds %3ldms %3ldus %3ldns %12ld", s, ms, us, ns, t);
  35. }
  36. int* read_int_array(unsigned n)
  37. {
  38. int* array = (int*)malloc(n * sizeof(unsigned));
  39. for (unsigned i = 0; i < n; ++i) {
  40. scanf("%i", &array[i]);
  41. }
  42. return array;
  43. }
  44. void read_input(int** array, unsigned* n)
  45. {
  46. if (isatty(0)) {
  47. printf("Enter n: ");
  48. }
  49. scanf("%u", n);
  50. if (isatty(0)) {
  51. printf("Enter %u integers: ", 2 * *n);
  52. }
  53. *array = read_int_array(2 * *n);
  54. }
  55. void print_array(int* array, unsigned n)
  56. {
  57. for (unsigned i = 0; i < n; ++i) {
  58. printf("%i%s", array[i], i == n - 1 ? "" : " ");
  59. }
  60. printf("\n");
  61. }