Quote:
> > I need to know how calculate the processor's clocks spent in executing a
> > set of C instructions (the spent time in ns).
[...]
> You can't.
[...]
> See, it's like this. Apart from some boring and tediously simple cases,
> C code doesn't correspond directly to the instructions of any particular
> machine, and the code that gets generated on some machine varies according
> to compiler settings (most obviously, the optimisation flags). What's more,
> the same sequence of instructions for the same processor family will take
> different numbers of processor ticks depending on details of the machine
> architecture, such as cache size and pipelining.
> So you can't do it in a system-independant way.
You are absolutely correct. But Juan is talking about "a _set_ of C
instructions" (which I interpret to mean "a set of C statements"), not
just one C statement. To simplify the task, we'll just assume that
Juan wants to time how long a function takes to run, because that's a
more common unit of code to time.
To be pedantic, it may be impossible to say how long any function will
take if that function is inlined, in which case its executable code may
be intertwined with another function's code. However, most C functions
will be in a separate chunk by itself.
Having said all that, the best way to do this is to see if your compiler
supports profiling (search your documentation for "profiling" or
"profiler). If that's not available, see if there are third party
profilers that support your compiler. Questions about those are best
asked in a platform-specific newsgroup instead.
Another way to do this is to get the time (see time.h) before you call
the function, and after you call the function. The difference between
the two times is how long it takes to run your function. Most platforms
would not support nanosecond-accuracy timing, so you may have to call
your function thousands or millions of times before you get an accurate
timing.
Quote:
> What you *can* do, on most implementations, is ask your C compiler to
> show you the generated code, and then get a local expert to analyse
> that, and (after they're picked themselves up off the floor after either
> hyterical laughter or copious vomiting having seen the quality of the
> generated code, which they will do no matter how good it is) tell you
> the timings you can expect and the conditions you can expect them in.
> Of course, it's possible that's not really what you need to do at all.
> Why do you think you need to calculate clock-ticks?
Other caveats:
1. Don't assume a function is the bottleneck. Profile widely and make
sure first.
2. Don't profile too early. You may still make significant changes to
the code, and invalidate all your results or mislead yourself.
3. Don't assume that optimizing a single function is the best way to
improve performance. Sometimes it's much better to modify the
_callers_ of that function to not call it so often.