<p>How can you measure the amount of time a function will take to execute? </p>

<p>This is a relatively short function and the execution time would probably be in the millisecond range.</p>

<p>This particular question relates to an embedded system, programmed in C or C++.</p>

[{'answer_id': 68919, 'author': 'Galen', 'author_id': 7894, 'author_profile': 'https://Stackoverflow.com/users/7894', 'pm_score': 2, 'selected': False, 'text': '<pre><code>start_time = timer\nfunction()\nexec_time = timer - start_time\n</code></pre>\n'}, {'answer_id': 68925, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 2, 'selected': False, 'text': '<p>Invoke it in a loop with a ton of invocations, then divide by the number of invocations to get the average time.</p>\n\n<p>so:</p>\n\n<pre><code>// begin timing\nfor (int i = 0; i &lt; 10000; i++) {\n    invokeFunction();\n}\n// end time\n// divide by 10000 to get actual time.\n</code></pre>\n'}, {'answer_id': 68938, 'author': 'cschol', 'author_id': 2386, 'author_profile': 'https://Stackoverflow.com/users/2386', 'pm_score': 4, 'selected': True, 'text': "<p>The best way to do that on an embedded system is to set an external hardware pin when you enter the function and clear it when you leave the function. This is done preferably with a little assembly instruction so you don't skew your results too much. </p>\n\n<p>Edit: One of the benefits is that you can do it in your actual application and you don't need any special test code. External debug pins like that are (should be!) standard practice for every embedded system.</p>\n"}, {'answer_id': 68945, 'author': 'Todd Gamblin', 'author_id': 9122, 'author_profile': 'https://Stackoverflow.com/users/9122', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re looking for sub-millisecond resolution, try one of these timing methods.  They\'ll all get you resolution in at least the tens or hundreds of microseconds:</p>\n\n<p>If it\'s embedded Linux, look at Linux timers:</p>\n\n<p><a href="http://linux.die.net/man/3/clock_gettime" rel="nofollow noreferrer">http://linux.die.net/man/3/clock_gettime</a></p>\n\n<p>Embedded Java, look at nanoTime(), though I\'m not sure this is in the embedded edition:</p>\n\n<p><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#nanoTime()" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#nanoTime()</a></p>\n\n<p>If you want to get at the hardware counters, try PAPI:</p>\n\n<p><a href="http://icl.cs.utk.edu/papi/" rel="nofollow noreferrer">http://icl.cs.utk.edu/papi/</a></p>\n\n<p>Otherwise you can always go to assembler.  You could look at the PAPI source for your architecture if you need some help with this.</p>\n'}, {'answer_id': 68949, 'author': 'stalepretzel', 'author_id': 1615, 'author_profile': 'https://Stackoverflow.com/users/1615', 'pm_score': 1, 'selected': False, 'text': '<p>In OS X terminal (and probably Unix, too), use "time":<br /></p>\n\n<pre><code>time python function.py\n</code></pre>\n'}, {'answer_id': 68963, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>If the code is .Net, use the stopwatch class (.net 2.0+) NOT DateTime.Now.  DateTime.Now isn't updated accurately enough and will give you crazy results</p>\n"}, {'answer_id': 68977, 'author': 'Joe Fontana', 'author_id': 73, 'author_profile': 'https://Stackoverflow.com/users/73', 'pm_score': 2, 'selected': False, 'text': "<p>if you're using linux, you can time a program's runtime by typing in the command line:</p>\n\n<pre><code>time [funtion_name]\n</code></pre>\n\n<p>if you run only the function in main() (assuming C++), the rest of the app's time should be negligible. </p>\n"}, {'answer_id': 68988, 'author': 'Benoit', 'author_id': 10703, 'author_profile': 'https://Stackoverflow.com/users/10703', 'pm_score': 3, 'selected': False, 'text': '<p>There are three potential solutions:</p>\n\n<p><strong>Hardware Solution</strong>:</p>\n\n<p>Use a free output pin on the processor and hook an oscilloscope or logic analyzer to the pin.  Initialize the pin to a low state, just before calling the function you want to measure, assert the pin to a high state and just after returning from the function, deassert the pin.</p>\n\n<pre><code>\n    *io_pin = 1;\n    myfunc();\n    *io_pin = 0;\n</code></pre>\n\n<p><strong>Bookworm solution</strong>:</p>\n\n<p>If the function is fairly small, and you can manage the disassembled code, you can crack open the processor architecture databook and count the cycles it will take the processor to execute every instructions.  This will give you the number of cycles required.<br>\nTime = # cycles * Processor Clock Rate / Clock ticks per instructions</p>\n\n<p>This is easier to do for smaller functions, or code written in assembler (for a PIC microcontroller for example)</p>\n\n<p><strong>Timestamp counter solution</strong>: </p>\n\n<p>Some processors have a timestamp counter which increments at a rapid rate (every few processor clock ticks).  Simply read the timestamp before and after the function.\nThis will give you the elapsed time, but beware that you might have to deal with the counter rollover.</p>\n'}, {'answer_id': 69053, 'author': 'Philibert Perusse', 'author_id': 7984, 'author_profile': 'https://Stackoverflow.com/users/7984', 'pm_score': 2, 'selected': False, 'text': '<h2>Windows XP/NT Embedded or Windows CE/Mobile</h2>\n\n<p>You an use the QueryPerformanceCounter() to get the value of a VERY FAST counter before and after your function. Then you substract those 64-bits values and get a delta "ticks". Using QueryPerformanceCounterFrequency() you can convert the "delta ticks" to an actual time unit. You can refer to MSDN documentation about those WIN32 calls.</p>\n\n<h2>Other embedded systems</h2>\n\n<p>Without operating systems or with only basic OSes you will have to:</p>\n\n<ul>\n<li>program one of the internal CPU timers to run and count freely. </li>\n<li>configure it to generate an interrupt when the timer overflows, and in this interrupt routine increment a "carry" variable (this is so you can actually measure time longer than the resolution of the timer chosen).</li>\n<li>before your function you save BOTH the "carry" value and the value of the CPU register holding the running ticks for the counting timer you configured.</li>\n<li>same after your function</li>\n<li>substract them to get a delta counter tick.</li>\n<li>from there it is just a matter of knowing how long a tick means on your CPU/Hardware given the external clock and the de-multiplication you configured while setting up your timer. You multiply that "tick length" by the "delta ticks" you just got.</li>\n</ul>\n\n<p><strong>VERY IMPORTANT</strong> Do not forget to disable before and restore interrupts after getting those timer values (bot the carry and the register value) otherwise you risk saving incorrect values.</p>\n\n<p><strong>NOTES</strong></p>\n\n<ul>\n<li>This is very fast because it is only a few assembly instructions to disable interrupts, save two integer values and re-enable interrupts. The actual substraction and conversion to real time units occurs OUTSIDE the zone of time measurement, that is AFTER your function.</li>\n<li>You may wish to put that code into a function to reuse that code all around but it may slow things a bit because of the function call and the pushing of all the registers to the stack, plus the parameters, then popping them again. In an embedded system this may be significant. It may be better then in C to use MACROS instead or write your own assembly routine saving/restoring only relevant registers.</li>\n</ul>\n'}, {'answer_id': 69166, 'author': 'Drew Frezell', 'author_id': 10954, 'author_profile': 'https://Stackoverflow.com/users/10954', 'pm_score': 2, 'selected': False, 'text': '<p>Depends on your embedded platform and what type of timing you are looking for.  For embedded Linux, there are several ways you can accomplish.  If you wish to measure the amout of CPU time used by your function, you can do the following:</p>\n\n<pre><code>#include &lt;time.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define SEC_TO_NSEC(s) ((s) * 1000 * 1000 * 1000)\n\nint work_function(int c) {\n    // do some work here\n    int i, j;\n    int foo = 0;\n    for (i = 0; i &lt; 1000; i++) {\n        for (j = 0; j &lt; 1000; j++) {\n            for ^= i + j;\n        }\n    }\n}\n\nint main(int argc, char *argv[]) {\n    struct timespec pre;\n    struct timespec post;\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID, &amp;pre);\n    work_function(0);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID, &amp;post);\n\n    printf("time %d\\n",\n        (SEC_TO_NSEC(post.tv_sec) + post.tv_nsec) -\n        (SEC_TO_NSEC(pre.tv_sec) + pre.tv_nsec));\n    return 0;\n}\n</code></pre>\n\n<p>You will need to link this with the realtime library, just use the following to compile your code:</p>\n\n<pre><code>gcc -o test test.c -lrt\n</code></pre>\n\n<p>You may also want to read the man page on <code>clock_gettime</code> there is some issues with running this code on SMP based system that could invalidate you testing.  You could use something like <code>sched_setaffinity()</code> or the command line <code>cpuset</code> to force the code on only one core.</p>\n\n<p>If you are looking to measure user and system time, then you could use the <code>times(NULL)</code> which returns something like a jiffies.  Or you can change the parameter for <code>clock_gettime()</code> from <code>CLOCK_THREAD_CPUTIME_ID</code> to <code>CLOCK_MONOTONIC</code>...but be careful of wrap around with <code>CLOCK_MONOTONIC</code>.</p>\n\n<p>For other platforms, you are on your own.</p>\n\n<p>Drew</p>\n'}, {'answer_id': 158220, 'author': 'selwyn', 'author_id': 16314, 'author_profile': 'https://Stackoverflow.com/users/16314', 'pm_score': 2, 'selected': False, 'text': '<p>I always implement an interrupt driven ticker routine.  This then updates a counter that counts the number of milliseconds since start up.  This counter is then accessed with a GetTickCount() function.  </p>\n\n<p>Example:</p>\n\n<pre><code>#define TICK_INTERVAL 1    // milliseconds between ticker interrupts\nstatic unsigned long tickCounter;\n\ninterrupt ticker (void)  \n{\n    tickCounter += TICK_INTERVAL;\n    ...\n}\n\nunsigned in GetTickCount(void)\n{\n    return tickCounter;\n}\n</code></pre>\n\n<p>In your code you would time the code as follows:</p>\n\n<pre><code>int function(void)\n{\n    unsigned long time = GetTickCount();\n\n    do something ...\n\n    printf("Time is %ld", GetTickCount() - ticks);\n}\n</code></pre>\n'}, {'answer_id': 158307, 'author': 'Ates Goral', 'author_id': 23501, 'author_profile': 'https://Stackoverflow.com/users/23501', 'pm_score': 2, 'selected': False, 'text': "<p>I repeat the function call a lot of times (millions) but also employ the following method to discount the loop overhead:</p>\n\n<pre><code>start = getTicks();\n\nrepeat n times {\n    myFunction();\n    myFunction();\n}\n\nlap = getTicks();\n\nrepeat n times {\n    myFunction();\n}\n\nfinish = getTicks();\n\n// overhead + function + function\nelapsed1 = lap - start;\n\n// overhead + function\nelapsed2 = finish - lap;\n\n// overhead + function + function - overhead - function = function\nntimes = elapsed1 - elapsed2;\n\nonce = ntimes / n; // Average time it took for one function call, sans loop overhead\n</code></pre>\n\n<p>Instead of calling function() twice in the first loop and once in the second loop, you could just call it once in the first loop and don't call it at all (i.e. empty loop) in the second, however the empty loop could be optimized out by the compiler, giving you negative timing results :)</p>\n"}]
['https://Stackoverflow.com/questions/68907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10703/']