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.7KB

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