Tick Tock: Building Clocks

One of my favorite things to do when learning a programming language, is to make a clock program.

      It may seem boring, like the infamous hello world examples that are strewn about the Internet. But writing a clock program can be very telling to what a programming language’s strengths and weaknesses are. At its bare minimum, a clock must be both Accurate and Efficient.

If we further break down these 2 categories:

The Accuracy of the clock, and the ease as to which this accuracy is acquired.       It can be very telling as to how quickly and efficiently a programming language can call resources. It is also telling as to how well said program can loop and step through that loop. As well as how many resources it takes to perform said operations.

The Efficiency aspect is telling as to how many CPU cycles, and how much RAM is needed for the program to run. It is also telling as to how much effort it takes to achieve a specific level of efficiency.

Here are some simple clock examples:


Python:

# Copyright 2016 Christopher Kruczek <krucz7@gmail.com>
#
#  This software is being distributed under the: 
#	GNU General Public License v3.
#	For full details of the license.
#	see: http://www.gnu.org/copyleft/gpl.html 
#
# Python Version: 3.5.2 
# 
# Description: A very simple clock. using a carriage return to constantly update the time.
# 			Also gracefully handles Ctrl+c termination.
# 
import time
from sys import stdout
WRITE = stdout.write# A lower level print function that takes less resources.
def disp_clock():
	"""Gets and displays time using a carriage return."""
	now = time.time()
	oldtime = time.time()
	try:
		while True:
			while now == oldtime:
				time.sleep(.25)# Program Waits for time to change.
				oldtime = now#   Sets new time as old time for the next loop. 
#				VV Displays time on the previously printed line. "Updates time."
				WRITE("\r"+time.strftime("%I:%M:%S %p",time.localtime(now)))
	except KeyboardInterrupt:# ------------- Gracefully handles ctrl+c interrupt to exit the program.
		print("\ngoodbye!")
		exit(0)
def main():
	"""The main program."""
	WRITE("Start time: "+time.strftime("%I:%M:%S %p",time.localtime(time.time()))+"\n")
	disp_clock()
main()

C++:

// Copyright 2016 Christopher Kruczek <krucz7@gmail.com>
//
//  This software is being distributed under the: 
//	GNU General Public License v3.
//	For full details of the license.
//	see: http://www.gnu.org/copyleft/gpl.html 
//
// Description: A simple cross platform clock program.
//		"It displays current time on a single line using a carriage return."
//		Checks for change in seconds to update clock display. 
//
//
// Building instructions: To compile via cli use: g++ clock.cpp -o run
//
//    TODO:
//         [Done] Make method/function to display 12hr time
//         [Done] Make loop to update time as it changes.
//         [Done] Make program sleep for allocated amount of time.
//
//         [Done] Make AM and PM indicator based on if else statement.
//
//
#include <iostream>//used for standard input and output.
#include <chrono>// used for sleep and time unit functions.
#include <ctime>//  used for time telling.
#include <thread>// used for sleep function.
#include <string>// used for management of strings.

using namespace std;
using namespace std::this_thread;
using namespace std::chrono;
void print_time(time_t now = time(0))
{
        tm *ltm = localtime(&now);// Enables usage of tm struct.
        int s_hour = 0;//            "standard" 12 hour format [hours variable].
        int h = ltm->tm_hour;//      System default "24 hr format" hours.
        string indicator;//          String used to indicate: am or pm.
        if ( h > 12)//               Used to display hours in 12hr am-pm format.
        {
                s_hour = h - 12;
                indicator = "PM ";
        } else
        {
                s_hour = h;
                indicator = "AM ";
        }// VV Prints the time in hour:minute:sec am/pm format.
        cout << "\r" 
        << s_hour      << ":"
        << ltm->tm_min << ":"
        << ltm->tm_sec << " " 
        << indicator;// AM - PM indicator.
        cout.flush();// flushes output to update displayed text on the screen.
}

int main()
{
	// VV Indicator for comparing current time to previous. to measure when the time changes for updating displayed time.
         time_t now = time(0);
         time_t curtime = time(0);
         while(true)// Loop forever, to count time.
         {
	// VV While past and current time's seconds are the same, loop until there is a change.
                while(localtime(&now)->tm_sec == localtime(&curtime)->tm_sec){
                        sleep_for(seconds(1));// Makes program wait for 1 second. "from library std::thread."
                        curtime = time(0);//     Update curtime.
                }// End of check for time change loop.
                print_time(curtime);
                now = curtime;// Update crrent time variable as now.
        }// End of while loop.


}// End of main.


PS: If you like the article image you can get it here

Note: This is a running list of languages. Additional languages will be added later.