LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-20-2019, 05:31 AM   #1
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.
Distribution: Currently OpenMandriva. Previously openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,071

Rep: Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574
A question about time...


Now I know what ya's are thinking... how's "time" a programming question? Well, good question (pun intended)... Basically I've been practicing some structures and loops and I thought, "well what better way than to create a clock". So I did, but before I get to my question, a little background...

Basically I wrote a little program that has a time structure for the hours, minutes, and seconds, with some loops to increment them. My first problem was that since time never stops, then setting a condition on the first loop (that houses my nested loops) would mean either, the loop would never run, or it would stop rather than continue to increment the time. So I didn't set a condition in the for loop's initialization field where you have the initial expression, condition, and the loop expression. But because it would therefore keep going forever, I wrote an if statement in the body of the first loop so it stops after 3 hours.

The second problem I had was that I DID have to set a condition for the two nested loops so when the seconds reach 60, the minute is incremented, and then the same so the hour gets incremented. But unless you reset the structure member for minutes and seconds back to zero once they reach 60, then the minutes and hours won't get incremented - so I did just that, and that solved that problem. Which brings me to my question and third problem...

Because the computer is fast, and doesn't take three hours to increment my loops, well one or two seconds (if even that) doesn't equal three hours. In other words; it doesn't take three hours to increment the time to three hours. I imagine the solution in regards to giving the computer the concept of "a second" involves some sort of math calculation, but I have no idea what that would even look like.

Here's my code:

Code:
#include <stdio.h>

int main(void) {
    
    int i;

    struct time {
         int hour, minute, second;
    };

    struct time now;

    now.hour = 0;
    now.minute = 0;
    now.second = 0;

    for ( i = 0; ; ++i ) {
          ++now.second;
          if ( now.hour == 3) {
              break;
          }
          while ( now.second == 61 ) {
                     now.second = 0;
                     ++now.minute;
          }
          while ( now.minute == 61 ) {
                     now.minute = 0;
                     ++now.hour;
          }
          printf("Time is now: %i:%i:%i\n", now.hour, now.minute, now.second);
    }
    
    printf("\nfor loop iterations: %i\n", i);

    return 0;
}
Here's how it works:

Code:
...
Time is now: 2:60:39
Time is now: 2:60:40
Time is now: 2:60:41
Time is now: 2:60:42
Time is now: 2:60:43
Time is now: 2:60:44
Time is now: 2:60:45
Time is now: 2:60:46
Time is now: 2:60:47
Time is now: 2:60:48
Time is now: 2:60:49
Time is now: 2:60:50
Time is now: 2:60:51
Time is now: 2:60:52
Time is now: 2:60:53
Time is now: 2:60:54
Time is now: 2:60:55
Time is now: 2:60:56
Time is now: 2:60:57
Time is now: 2:60:58
Time is now: 2:60:59
Time is now: 2:60:60
Time is now: 3:0:0

for loop iterations: 11163
Now clearly that took maybe not even one second. How do I give the code the concept of an actual second (that would be a "second" to you or me, eg. 1..2..3..etc, rather than 123456789,etc)?

James
 
Old 09-20-2019, 05:39 AM   #2
tyler2016
Member
 
Registered: Sep 2018
Distribution: Debian, CentOS, FreeBSD
Posts: 231

Rep: Reputation: Disabled
This should get you started. Check out some of the other pages in the See Also sections as well:

Code:
man 3 sleep
man 2 nanosleep
man 2 time


Basically, they use the hardware clock.

Last edited by tyler2016; 09-20-2019 at 05:40 AM.
 
2 members found this post helpful.
Old 09-20-2019, 05:43 AM   #3
michaelk
Moderator
 
Registered: Aug 2002
Posts: 19,028

Rep: Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890
FYI valid range for minutes,seconds is 0-59
 
2 members found this post helpful.
Old 09-20-2019, 06:23 AM   #4
syg00
LQ Veteran
 
Registered: Aug 2003
Location: Australia
Distribution: Lots ...
Posts: 18,127

Rep: Reputation: 2923Reputation: 2923Reputation: 2923Reputation: 2923Reputation: 2923Reputation: 2923Reputation: 2923Reputation: 2923Reputation: 2923Reputation: 2923Reputation: 2923
And down the rabbit hole we go ...
Let's not mention leap-thingies. Or Newton versus Einstein on these matters. Or GMT vs UTC - er UT1. And then there's UT0 and UT2 (so far).

Brave souls venture there.
 
1 members found this post helpful.
Old 09-20-2019, 06:41 AM   #5
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.
Distribution: Currently OpenMandriva. Previously openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,071

Original Poster
Rep: Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574
Quote:
Originally Posted by tyler2016 View Post
This should get you started. Check out some of the other pages in the See Also sections as well:

Code:
man 3 sleep
man 2 nanosleep
man 2 time
Basically, they use the hardware clock.
Thanks tyler2016, but while I'll have a look at the sleep() function; it seems like the easy way out, and I would like to know what the code would look like to give the computer the concept of "a second". I had a look at the source code for the sleep() function of libc here (I *think* it's the right file), but I don't know how to interpret most of it/what it's actually saying. I would like to at least try and understand it though.

Quote:
Originally Posted by michaelk View Post
FYI valid range for minutes,seconds is 0-59
Yeah, I was sorta thinking that, so I'll change my code to reflect that. Thanks michaelk!

Quote:
Originally Posted by syg00 View Post
And down the rabbit hole we go ...
Let's not mention leap-thingies. Or Newton versus Einstein on these matters. Or GMT vs UTC - er UT1. And then there's UT0 and UT2 (so far).

Brave souls venture there.
...and I ain't that brave yet, so no, I'll leave leap years, timezones, etc for later on...
 
Old 09-20-2019, 07:14 AM   #6
michaelk
Moderator
 
Registered: Aug 2002
Posts: 19,028

Rep: Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890
It's a bit more complicated but the origins of the system clock is basically an interrupt that increments a counter. The date command reads the counter and converts it to human value of date time.

Basically you can poll the counter in a loop to see when a second has elapsed or create an interrupt. Never tried the later using bash. Sleep is easier.
 
3 members found this post helpful.
Old 09-20-2019, 07:32 AM   #7
rtmistler
Moderator
 
Registered: Mar 2011
Location: MA, USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 8,038
Blog Entries: 13

Rep: Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488
Quote:
Originally Posted by jsbjsb001 View Post
Now I know what ya's are thinking... how's "time" a programming question?
I would suggest a better thread title.

Is the question answered by the way? I feel it may be.

Please realize that keeping accurate time with a very precise resolution are things which the OS does, there are hardware assists, and there are also reference clocks. You may find that the emulation of a single second is absolutely accurate for your needs. Will definitely point out that you'll see complications if you write a program which is intended to take several thousands of seconds, but to a predictable limit so that you can predict the time of completion, but find that the reality versus the calculated prediction may be off by some error of time. Therefore you can waste volumes of effort, working to attain some highest degree of precision, which I feel may turn out to be non-realistic with a general purpose OS, and also user space programming.
 
Old 09-20-2019, 07:59 AM   #8
tyler2016
Member
 
Registered: Sep 2018
Distribution: Debian, CentOS, FreeBSD
Posts: 231

Rep: Reputation: Disabled
Here are a few interesting write ups on time keeping:

https://www.eecis.udel.edu/~ntp/ntpf...-sw-clocks.htm
https://www.engineersgarage.com/how_...omputer-works/

Don't forget about NTP which is used to fix the inaccuracies when they inevitably occur.
 
2 members found this post helpful.
Old 09-20-2019, 09:40 AM   #9
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.
Distribution: Currently OpenMandriva. Previously openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,071

Original Poster
Rep: Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574
Quote:
Originally Posted by rtmistler View Post
I would suggest a better thread title.

Is the question answered by the way? I feel it may be.

Please realize that keeping accurate time with a very precise resolution are things which the OS does, there are hardware assists, and there are also reference clocks. You may find that the emulation of a single second is absolutely accurate for your needs. Will definitely point out that you'll see complications if you write a program which is intended to take several thousands of seconds, but to a predictable limit so that you can predict the time of completion, but find that the reality versus the calculated prediction may be off by some error of time. Therefore you can waste volumes of effort, working to attain some highest degree of precision, which I feel may turn out to be non-realistic with a general purpose OS, and also user space programming.
I believe I did explain what I'm trying to ask here, the thread is about "time". So not sure a different title would make much difference.

Well, yes and no. Yes I now know I could use the sleep() function to get the concept of "a second" in my program. But no, it doesn't really explain how that's actually done, let alone, what the code for the sleep() function is actually saying/doing. Yes, I can see a structure there, a do loop, some if/else statements, a while loop, but beyond that, it doesn't make any sense to me WHAT that code is actually doing. So again, I would like to have at least slightly better understanding of that code than that.

Yes, I do realize that the OS deals with the time and date, but I still would like to understand a little more about it from the programming perspective. So while I think I understand your point, and while I'm not looking to write any kernels just yet, I'd still like a better understanding of what makes the computer see "a second" as "a second" in the same way you or I would see "a second", and how the sleep() function actually works (as in: the code behind it).

Thanks again tyler2016, nice articles!

So basically the kernel gets the time for the "software clock" from the "hardware clock/RTC", and if I say change the time with the date command, this updates the hardware clock, which in turn updates the "software clock"?

Can anyone give me some clue as to how I'm supposed to interpret the code for what I assume is the code for the sleep() function, that I linked in post #5?
 
Old 09-20-2019, 10:46 AM   #10
michaelk
Moderator
 
Registered: Aug 2002
Posts: 19,028

Rep: Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890
A bit off topic IMHO but the system clock is basically a counter that starts at zero. The purpose of the hardware clock is set the system clock to the actual time at boot up. Now days embedded systems like the Pi don't have a RTC and rely upon a clock daemon to set the system time via the network.

The date command only changes system time. You can manually sync the hardware clock to system clock or vice versa with the hwclock command. ntp does update the hardware clock.

The purpose of the sleep command is to pause the running process for a set period of time using a high precision timer.
http://git.savannah.gnu.org/cgit/cor...ee/src/sleep.c
https://github.com/torvalds/linux/bl...rs/nanosleep.c

Here is a history of how the system clock works.
https://linux.die.net/man/7/time

Just for reference on real time clocks.
https://en.wikipedia.org/wiki/Real-time_clock

I want one...
https://en.wikipedia.org/wiki/Chip-scale_atomic_clock

Last edited by michaelk; 09-20-2019 at 11:05 AM.
 
1 members found this post helpful.
Old 09-20-2019, 01:56 PM   #11
rtmistler
Moderator
 
Registered: Mar 2011
Location: MA, USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 8,038
Blog Entries: 13

Rep: Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488
I do not feel it's off topic at all michaelk, in fact it's very applicable for you to point out the very involved details with keeping accurate system time.

And to whit, the chip scale atomic clock raises the point of precision which is extremely important for time keeping:
Quote:
can keep time to within 100 microseconds per day after several years of operation
As I'm sure you know, and I feel may be a new topic for jsb, this capability is EXTREMELY unusual in an RTC device.

If you experiment with RTCs and projects involving adding one to an Arduino (or Beagle/Raspberry Pi/Humminboard/Esp32/you name it): Interface DS3231 Precision RTC Module with Arduino containing the section:
Quote:
The main difference between the DS3231 and DS1370 is the accuracy of time-keeping.

DS1307 comes with an external 32kHz crystal for time-keeping whose oscillation frequency is easily affected by external temperature. This usually results with the clock being off by around five or so minutes per month.

However, the DS3231 is much more accurate, as it comes with an internal Temperature Compensated Crystal Oscillator(TCXO) which isnít affected by temperature, making it accurate down to a few minutes per year at the most
This is what embedded programmers many times end up considering. The extremely cheap SOM or SOC does not come with a RTC, the intended product will be IoT enabled, however there is a requirement to maintain time over reboots or power cycles, as well as persist if NTP fails. Or they wish it to maintain clock via battery, but the device may be off for extended periods of time. The device may not be network attached, say it is a Bluetooth sensor embedded in a wall and a technician attaches to it via a mobile device, ... on occasion, ... because these babies are supposed to last a minimum of 2+ years. Therefore why pay expensive money to have the technician visit a site daily, when every few months may suffice. Losing a few seconds per month is a very common problem, and is also frowned upon by the record keepers. Why? Well, if they download data from several devices which are minutes apart in clocks, they cannot correlate data as readily as they would like to, and they have to fix it at the server level. Once again, there are software solutions, such as updating the sensor time at point of attachment. Meanwhile this does something to the captured records in the device, what if the clock didn't lost time, but instead gained time and when it attached to the mobile its time got rewound? Well then the latest sensor records may not be advertised, because "they haven't happened yet", or worse, they might be overwritten by a following sensor event. Etc, etc. And what do you do if you happen to have 1,000 sensor events all with time records included. What do you do? Burn up sensor battery to fix that now? Or download the data, fix it later? Either case, someone complains.

I think based on the evolution of the question, my take on an answer would be to point out that time kept by a computer is based on several things:
  1. Battery backed HW RTC
  2. NTP use which updates the HW clock and saves the new data.
  3. OS and application software which ensures that the user experience is not confusing.
And all the references offered by many here are applicable.

It really does depend how far you wish to stretch this topic.

As well as how much time you have.
 
Old 09-20-2019, 03:10 PM   #12
michaelk
Moderator
 
Registered: Aug 2002
Posts: 19,028

Rep: Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890
Quote:
It really does depend how far you wish to stretch this topic.

As well as how much time you have.
Very true...

Time is complicated and like syg00 posted can be a very deep rabbit hole.
 
Old 09-21-2019, 12:10 AM   #13
jsbjsb001
Senior Member
 
Registered: Mar 2009
Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.
Distribution: Currently OpenMandriva. Previously openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,071

Original Poster
Rep: Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574Reputation: 1574
Ok, so I added the sleep() function to my program and it does make the time far more accurate, and solves the problem of "a second" the same as it is to you and me.

But, while I'm not looking to become a "time expert" for now... I would still like to understand exactly how the computer gets the concept of "a second". So on that point: is it right to say that the kernel reads the "hardware clock/RTC", that in turn gives the "software/system clock" the time, and that's how the kernel/system knows what "a second" actually means/is? And the sleep() function looks at the kernel's time data structure to figure out what "a second" is ?

And I'd be grateful if someone could help me understand the code for the sleep() function, so I can at least get a rough idea of what's going on there. Can anyone even just explain that even just a "high-ish" level ?

And also, how do you have printf display just one line without putting it in a loop, so it still updates the value of the member variables when their incremented? Can you do that?

Here's my modified code:

Code:
#include <stdio.h>
#include <unistd.h>

int main(void) {
    
    int i;

    struct time {
         int hour, minute, second;
    };

    struct time now;

    now.hour = 0;
    now.minute = 0;
    now.second = 0;

    for ( i = 0; ; ++i ) {
          sleep(1);
          ++now.second;
          if ( now.hour == 3 ) {
              break;
          }
          while ( now.second == 60 ) {
                     now.second = 0;
                     ++now.minute;
          }
          while ( now.minute == 60 ) {
                     now.minute = 0;
                     ++now.hour;
          }
          printf("Time is now: %i:%i:%i\n", now.hour, now.minute, now.second);
    }
    
    printf("\nfor loop iterations: %i\n", i);

    return 0;
}

Last edited by jsbjsb001; 09-21-2019 at 12:13 AM. Reason: added last question about printf
 
Old 09-21-2019, 05:45 AM   #14
michaelk
Moderator
 
Registered: Aug 2002
Posts: 19,028

Rep: Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890Reputation: 2890
Quote:
But, while I'm not looking to become a "time expert" for now... I would still like to understand exactly how the computer gets the concept of "a second". So on that point: is it right to say that the kernel reads the "hardware clock/RTC", that in turn gives the "software/system clock" the time, and that's how the kernel/system knows what "a second" actually means/is?
Lets ignore the hardware clock for now. CPUs and digital circuits are controlled by a clock signal which is basically a high frequency square wave generator. This clock signal is generated by a crystal oscillator circuit.

In a simple microprocessor by todays standards you can see how the clock signal controls execution. From reading memory to loading into the microprocessor to executing the instruction.

http://www.zseries.in/embedded%20lab...p#.XYXxqpxOlN0

Quote:
The system clock is typically implemented as a programmable interval timer that periodically interrupts the CPU, which then starts executing a timer interrupt service routine. This routine typically adds one tick to the system clock (a simple counter) and handles other periodic housekeeping tasks (preemption, etc.) before returning to the task the CPU was executing before the interruption.
https://en.wikipedia.org/wiki/System_time

In simple terms the CPU as built in timers and after so many clock cycles an internal CPU register is incremented. One of these registers is the system time. Each bit has a value and typically with modern computers it is nanoseconds or microseconds. When the counter is zero it is assigned midnight 1 January 1970 UTC which is known as the epoch time. The definition of system time is the number of seconds since the epoch. This is how a computer gets the concept of a second.

Again in simple terms when a computer boots everything is initialized to some value and system time is zero. To make things easier for the user
a battery backed clock was designed on the motherboard so one did not have to always enter the date/time. At boot up the hardware clock is read converted to seconds UTC since epoch and stored in the system time counter.

Just as an aside not all operating systems or software defines the epoch the same date/time.
 
1 members found this post helpful.
Old 09-21-2019, 05:48 AM   #15
rtmistler
Moderator
 
Registered: Mar 2011
Location: MA, USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 8,038
Blog Entries: 13

Rep: Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488Reputation: 3488
Recommend you please read the sleep.c code references by michaelk (post #10) and ask more specific questions, the file is under 200 lines of code, much of which are defines.

You can put printf wherever you wish, what's wrong with it right now?
 
  


Reply

Tags
c programming, time


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
how to understand user time, sys time, wait time, idle time of CPU guixingyi Linux - Server 1 08-24-2010 10:10 AM
System time vs Hardware time and Daylight Savings Time Toadman Linux - General 6 03-17-2007 08:12 AM
System time vs Hardware time and Daylight Savings Time Toadman Linux - Networking 6 03-16-2007 07:14 PM
Time, time, time raylhm SUSE / openSUSE 5 11-02-2006 03:15 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 10:52 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration