Thread: clock_gettime problem

  1. #1
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193

    Question clock_gettime problem

    Good morning. I wrote the following code:

    Code:
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <time.h>
    
    struct timespec ts;
    
    int main() 
    { 
      int value;
      srand(clock_gettime(CLOCK_REALTIME, &ts));
      value = rand();    
      printf("\nThe value: %d\n", value);    
      return 0;    
    }
    I try to get a random int but I always get the same value when I compile the program with gcc -g rand.c -o rand -lrt

    The value: 1804289383

    What am I doing wrong?

    I already tried with CLOCK_MONOTONIC too.

  2. #2
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    clock_gettime() returns an int value of 0 to indicate success (and an int value of -1 to indicate failure). It is that 0 value that you are using to initialize the PRNG.

    I suggest you redo your program to use (parts of) the structure ts.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You didn't read the manual for starters.

    clock_gettime(3): clock/time functions - Linux man page
    Return Value

    clock_gettime(), clock_settime() and clock_getres() return 0 for success, or -1 for failure (in which case errno is set appropriately).
    You're getting the same answer each time, because it returns success/fail each time.

    This isn't the same as time()
    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.

  4. #4
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193
    I got it. Many thanks

    Code:
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <time.h>
    
    int main() 
    { 
      int value;
      srand(time(NULL));
      value = rand();    
      printf("\nThe value: %d\n", value);    
      return 0;    
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sleep() function problem or logic problem?
    By FernandoBasso in forum C Programming
    Replies: 7
    Last Post: 11-16-2011, 05:50 PM
  2. strcmp problem, whats the problem, i cant figure it out!
    By AvaGodess in forum C Programming
    Replies: 14
    Last Post: 10-18-2008, 06:45 PM
  3. Replies: 4
    Last Post: 10-16-2008, 07:30 PM
  4. Visual Studio Linker problem or my problem?
    By OOPboredom in forum C Programming
    Replies: 2
    Last Post: 04-13-2004, 12:32 AM
  5. syntax linked list problem & struct problem
    By beely in forum C Programming
    Replies: 5
    Last Post: 11-11-2002, 09:14 AM