使用2个线程中的clock_gettime测量时间

时间:2017-11-12 18:10:59

标签: c

我正在使用clock_gettime(CLOCK_MONOTONIC,& ts_start / end)来测量在2个线程中运行的任务的主程序中的时间。我正在使用pthread

然而,第一个线程的时间比第二个线程更高(不可能是真的),第二个线程显示了执行的实时性。

这与CLOCK_MONOTONIC有关吗?使用CLOCK_MONOTONIC_RAW会更好吗?

这是我的代码段。与第二个线程相比,第一个线程中的ts_end.tv_sec非常大。这不可能是真的。有些事情不对......

/* this function is run by the second thread */
static void *writeToiMM(void *threadarg)
{
    struct arg_struct  *args = threadarg;
    test_xsd("/dev/abc/xsd0", args->address, args->size, args->offset, args->count, args->filename);
    pthread_exit(NULL);
    return NULL;
}

int main(int argc, char* argv[])
{
  pthread_t xsd_thread;
  if (pthread_create(&xsd_thread, NULL, writeToiMM, &args) != 0) {
        printf("Uh-oh!\n");
        return -1;
  }
  test_xsd(device, address, size, offset, count, args.filename);

  if(pthread_join(xsd_thread, NULL)) {
    fprintf(stderr, "Error joining thread\n");
    return -1;
}

}

/* Subtract timespec t2 from t1*/
static void timespec_sub(struct timespec *t1, const struct timespec *t2)
{
  assert(t1->tv_nsec >= 0);
  assert(t1->tv_nsec < 1000000000);
  assert(t2->tv_nsec >= 0);
  assert(t2->tv_nsec < 1000000000);
  t1->tv_sec -= t2->tv_sec;
  t1->tv_nsec -= t2->tv_nsec;
  if (t1->tv_nsec >= 1000000000)
  {
    t1->tv_sec++;
    t1->tv_nsec -= 1000000000;
  }
  else if (t1->tv_nsec < 0)
  {
    t1->tv_sec--;
    t1->tv_nsec += 1000000000;
  }
}

static int test_xsd(char *devicename, uint32_t addr, uint32_t size, uint32_t offset, uint32_t count, char *filename)
{
  int rc;
  char *buffer = NULL;
  char *allocated = NULL;
  struct timespec ts_start, ts_end;

  posix_memalign((void **)&allocated, 4096/*alignment*/, size + 4096);
  assert(allocated);
  buffer = allocated + offset;
  printf("host memory buffer = %p\n", buffer);

  int file_fd = -1;
  int asc_fd = open(devicename, O_RDWR);
  assert(asc_fd >= 0);

  if (filename) {
    file_fd = open(filename, O_RDONLY);
    assert(file_fd >= 0);
  }
  /* fill the buffer with data from file? */
    if (file_fd >= 0) {
      /* read data from file into memory buffer */
      rc = read(file_fd, buffer, size);
      if (rc != size) perror("read(file_fd)");
      assert(rc == size);
    }
    off_t off = lseek(asc_fd, addr, SEEK_SET);
    rc = clock_gettime(CLOCK_MONOTONIC, &ts_start); //CLOCK_MONOTONIC_RAW 
    rc = write(asc_fd, buffer, size); // returns the number of bytes written to the file 
    assert(rc == size);
    rc = clock_gettime(CLOCK_MONOTONIC, &ts_end);

  /* subtract the start time from the end time */
  timespec_sub(&ts_end, &ts_start);
  /* display passed time, a bit less accurate but side-effects are accounted for */
  printf("CLOCK_MONOTONIC reports %ld.%09ld seconds (total) for last passed time\n",
    ts_end.tv_sec, ts_end.tv_nsec, size);

  close(asc_fd);
  if (file_fd >= 0) {
    close(file_fd);
  }
  free(allocated);
}

0 个答案:

没有答案