1

Am I going mad? I'm running this on x86_64.

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    printf("Clock: %f\n", clock() / (double)CLOCKS_PER_SEC);
    sleep(1);
    printf("Clock: %f\n", clock() / (double)CLOCKS_PER_SEC);
    sleep(1);
    printf("Clock: %f\n", clock() / (double)CLOCKS_PER_SEC);
    return 0;
}

This prints

Clock: 0.002880
Clock: 0.002968
Clock: 0.003019

It clearly waits for a second at the sleep(1) lines, but the output is clearly wrong.

If that doesn't work, is there a portable C alternative?

joerick
  • 16,078
  • 4
  • 53
  • 57

2 Answers2

5

I'm an idiot. clock() returns processor time used.

joerick
  • 16,078
  • 4
  • 53
  • 57
  • yup and since it's sleeping it's probably not using any :) – iabdalkader Nov 22 '12 at 10:36
  • 1
    For the record, I was following documentation here http://www.cplusplus.com/reference/clibrary/ctime/clock/, I've written to them to inform them of their error! – joerick Nov 22 '12 at 10:41
  • @joerick Just use cppreference.com. They contain very few such errors and if you find one, you can fix it right there. –  Nov 22 '12 at 23:19
0

You can declare an variable time_t t1,t2; t1 = time(NULL); sleep(1); t2 = time(NULL); You can debug and view the values of t1 and t2. I think you can take an reference from http://www.cplusplus.com/reference/clibrary/ctime/time/