-2

I tried this, but it doesn't work well, it shows a number like 0.000053

    begin = clock();
    scanf(" %c", &in);
    end = clock();
    printf("%f\n", (double)(end - begin) / CLOCKS_PER_SEC);
betseg
  • 165
  • 5
  • 13
  • 1
    What did you expect to happen instead? – zwol Feb 17 '16 at 20:41
  • If you replace both calls to `clock()` with `time(0)` and remove the `/ CLOCKS_PER_SEC` part, does it do something more like what you expected? (Note: this change is technically not guaranteed even to compile, but the odds are overwhelmingly that it will be fine.) – zwol Feb 17 '16 at 20:43
  • Incidentally: [`scanf` is broken-as-specified, and can't be safely used for many of the things people want to use it for](https://stackoverflow.com/questions/24302160/scanf-on-an-istream-object/24318630#24318630); the precise thing you are doing with it happens to be safe, but I strongly recommend you get out of the habit of using it at all. – zwol Feb 17 '16 at 20:44
  • I expected seconds - as in [here](http://stackoverflow.com/questions/459691/best-timing-method-in-c) – betseg Feb 17 '16 at 20:44
  • btw i code in c, not c++ – betseg Feb 17 '16 at 20:46
  • time(0) works better, but starts counting after first input – betseg Feb 17 '16 at 20:49
  • The linked post talks about both C and C++, and its criticism of `scanf` applies equally to both languages, since the C++ standard doesn't make any changes to the specification of `scanf`. – zwol Feb 17 '16 at 20:51
  • I don't understand what you mean by "`time` starts counting after first input." – zwol Feb 17 '16 at 20:53
  • ./program, wait 5 seconds, write something, wait 5 seconds more, press enter, output is "5" – betseg Feb 17 '16 at 20:55
  • "it shows a number like 0.000053" looks right. What value did you expect? Wall time as in [this answer](http://stackoverflow.com/a/35467466/2410359) or something else? Without this clarity the question is unclear. – chux - Reinstate Monica Feb 17 '16 at 21:45

1 Answers1

3

clock measures "CPU time," not "wall-clock time." The difference is (approximately) that CPU time does not include time spent waiting for something to happen. 0.000053 seconds (53 microseconds) is in the right ballpark for the amount of CPU time consumed by this use of scanf -- no matter how long you waited before you pressed Enter.

time, gettimeofday, and clock_gettime(CLOCK_MONOTONIC) (in increasing order of precision) measure wall-clock time. If you need to measure wall-clock time, use one of those.

zwol
  • 135,547
  • 38
  • 252
  • 361