I usually do the following to measure time differences:
        struct timespec tp;
        uint64_t starttime;

        clock_gettime(CLOCK_MONOTONIC, &tp);
        starttime = ((uint64_t)(tp.tv_sec) * 1000000) + tp.tv_nsec / 1000;
        //do something
        clock_gettime(CLOCK_MONOTONIC, &tp);
        uint64_t timeconsumed = (((uint64_t)(tp.tv_sec) * 1000000) + tp.tv_nsec 
/ 1000 - starttime) / 1000;

This requires CONFIG_CLOCK_MONOTONIC to be configured.
This is immune to (wall)clock updates.
Result is in usec, but not necessarily in usec granularity.

On Fri, Apr 30, 2021 at 02:07:15AM +0900, yuta wrote:
> Brennan,
> Thank you for your advice.
> 
> I checked links you shared and 
> https://www.gnu.org/software/libc/manual/html_node/CPU-Time.html
> I got elapsed time. Thank you.
> 
> However I'm wondering why the elapsed time I got was not exactly the same I 
> expected to get.
> I tried below.
> 
> // ***** start
> clock_t start, end;
> double cpu_time_used;
> 
> start = clock();
> usleep(1000000); // 1sec
> end = clock();
> 
> cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
> 
> printf("CPU time used: %f sec\n", cpu_time_used);
> // ***** end
> 
> What I got is ...
> "CPU time used: 1.010000 sec" (I expected to get 1.000000 sec)
> 
> Do you have any idea?
> 
> Yuta Ide
> 
> On 2021/04/30 0:30, Brennan Ashton wrote:
> > On Thu, Apr 29, 2021, 8:16 AM yuta <yutr...@gmail.com> wrote:
> >
> >> Hi all.
> >>
> >> I'm new to NuttX.
> >>
> >> I'm not sure if it's no problem me asking some personal question about
> >> NuttX here. (please tell me if better place to ask.)
> >>
> >> by the way, I have made my app in apps/examples/<my app>. It's working
> >> well.  Now, I would like to measure elapsed time during processing a
> >> program by put codes like below.
> >>
> > NuttX supports the POSIX time interfaces so you are looking for something
> > like this.
> >
> > https://www.gnu.org/software/libc/manual/html_node/Calculating-Elapsed-Time.html
> >
> >
> > There is also CPU time measurements, but NuttX does not treat this exactly
> > correct as it is expected to give the amount of clock ticks the CPU has
> > spent on a process. Instead with NuttX you get ticks since boot.
> >
> > https://www.gnu.org/software/libc/manual/html_node/Processor-And-CPU-Time.html
> >
> > --Brennan
> >

-- 
B.Walter <be...@bwct.de> http://www.bwct.de
Modbus/TCP Ethernet I/O Baugruppen, ARM basierte FreeBSD Rechner uvm.

Reply via email to