Thread: Get time in nanoseconds

  1. #1
    Registered User
    Join Date
    Jun 2017
    Posts
    3

    Get time in nanoseconds

    Hello


    The following code calculates the values in nanoseconds:

    Code:
             for(int i=1; i<=39; i++){
                 long startTime = java.lang.System.nanoTime();         
                 System.out.println("Hello world");
                 long endTime = java.lang.System.nanoTime();
                 System.out.println((endTime - startTime)); 
             }
    I would like to do the same in C:
    There are some code examples in the internet such as:

    Code:
    #include <sys/time.h>
    #include <stdio.h>
    #include <unistd.h>
    int main()
    {
        struct timeval start, end;
        long mtime, seconds, useconds;
    
        for(int sx=1; sx<=39; sx++){
    
            gettimeofday(&start, NULL);
            printf("Hello world");
            gettimeofday(&end, NULL);
    
            printf("Elapsed time: %ld microsecons\n", end.tv_usec - start.tv_usec);
    
         }
    
        return 0;
    }
    Unfortunately this returns a 0 microseconds value. And a multiplication of 1000 doesn't change at all.

    Can anyone help please?

    Thx,
    Troix

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Calculate time in microseconds or nanoseconds
    No need to keep spamming the board just because your first post got put into a moderation queue.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Calculate time in microseconds or nanoseconds
    By Troix in forum C Programming
    Replies: 3
    Last Post: 06-05-2017, 09:40 AM
  2. Replies: 5
    Last Post: 04-17-2013, 11:32 PM
  3. Replies: 2
    Last Post: 04-17-2013, 12:25 AM
  4. get nanoseconds
    By kspen in forum C++ Programming
    Replies: 7
    Last Post: 04-01-2012, 10:48 AM
  5. count execution time in ubuntu(nanoseconds)
    By nik in forum C++ Programming
    Replies: 3
    Last Post: 04-07-2011, 07:20 PM

Tags for this Thread