Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • Normally you don't want to time printf("factorial ... %d), but that's what this code is doing. Of course, 10! is so fast to calculate compared to measurement overhead of clock() that you're not going to get much from timing just the computation. If the compiler doesn't constant-propagate through the loop to just print a constant j value; See also Idiomatic way of performance evaluation? re: the necessity of compiling with optimization, but also of having the work not optimize away. Commented Feb 14, 2023 at 5:50
  • Also, clock measures user-space CPU time for this process, not wall-clock time. That might be what you want if you don't want to time I/O waits. Commented Feb 14, 2023 at 5:51
  • This answer doesn't seem to add anything over an existing answer with a similar print macro. Commented Feb 14, 2023 at 6:02
  • Thank you Peter for your comments, but the answer is not 100% repeated, TICK TOCK method will define multiple variables if you need to measure multiple parts of code in the same function (like in main), then it's better to define one variable t, initiate it with clock() every time before measurement then call the macro, and so on. And Regarding the for loop of factorial, this is just a sample, feel free to replace it with a recursion version of the factorial function if you want. Commented Feb 15, 2023 at 6:03
  • The main reason I downvoted was for the bad example of how to use this macro, with printf inside the timed region. At least fix that or discuss in text that you're intentionally benchmarking I/O, if you think this answer adds value. Agreed that the macro details are a bit different, and declaring vars inside the TICK() macro isn't great for some use-cases. Multiple separate clock_t vars that aren't used at the same time is basically not a problem for optimizers, so it's just a matter of style. Commented Feb 15, 2023 at 6:08