Saturday, December 5, 2015

Performance Comparison of C, Swift, Go and Python

To compare the performance of different languages, let us write a simple algorithm that does the following. Say the given number is 5. Then the algorithm calculates the sum of all numbers for numbers from 1 to 5.
1+ (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35

C Program - test.c:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
  long sum = 0;
  int V = atoi(argv[1]);
  for (int C=1; C<=V; ++C) {
    for (int c=1; c<C+1; ++c)  {
        sum = sum + c; 
  printf("sum = %li\n",sum);
  return 0;

Swift Program - test.swift:

  var sum = 0;
  var V = Int(Process.arguments[1])
  for var C = 1; C <= V; ++C { 
      for var c = 1; c < C+1; ++c { 
        sum = sum + c;
  print("sum = \(sum)");

Go Program - test.go:
package main
import "os"
import "fmt"
import "strconv"
func main() {
 sum := 0
 V,err := strconv.Atoi(os.Args[1])
for I:=1; I<=V; I++ {
  for i:=1; i<I+1; i++ {
  sum = sum + i
if err == nil {
fmt.Println("sum =",sum)}

Python C extension: Say we want to create a module named "pal" with a function called "f1" to just do the same as test.c

Step 1. Create a file called "palmodule.c" :
#include <Python.h>
static PyObject * pal_f1(PyObject *self, PyObject *args)
  int x;
  PyArg_ParseTuple(args, "i", &x);
  long sum = 0;
  for (int C=1; C<=x; ++C) 
    for (int c=1; c<C+1; ++c)
        sum = sum + c;
  return Py_BuildValue("l", sum);

static PyMethodDef PalMethods[] = {

  {"f1", pal_f1, METH_VARARGS},

static struct PyModuleDef palmodule = {

   "pal",   /* name of module */
   "", /* module documentation, may be NULL */
   -1,       /* size of per-interpreter state of the module,
                or -1 if the module keeps state in global variables. */

PyMODINIT_FUNC PyInit_pal(void)

    return PyModule_Create(&palmodule);


Step 2. Create a file called ""
from distutils.core import setup, Extension
setup(name='pal', version='1.0', ext_modules=[Extension('pal', ['palmodule.c'])])         

Step 3. Install the extension using the following command:

sudo python3 install

 Step 4. Now write a python program "" using the pal module:

from sys import argv
from pal import f1
print("sum = %s" %f1(int(argv[1])))

Runtime Performance Comparison 

Run the above four different programs one by one and find the time taken as shown below. The number used is 100,000 :

1. C program

$ time ./test.o 100000
sum = 166671666700000
real 0m10.999s
user 0m10.992s
sys 0m0.000s

2. Swift program
$  time ./test.sw 100000
sum = 166671666700000
real 0m19.318s
user 0m19.304s
sys 0m0.000s

3. Go program

$  time ./test.g 100000
sum = 166671666700000
real 0m2.155s
user 0m2.152s
sys 0m0.004s

3. Python C extension program
time ./ 100000
sum = 166671666700000
real 0m1.618s
user 0m1.616s
sys 0m0.000s

This shows that Python with C extension is the best that takes the least time. The second best is "Go", then "C". Swift is the worst among them.


Sunday, October 4, 2015

Upstart Job Setup in Ubuntu

At Ubuntu start-up, say you want to to adjust brightness, you can add an upstart job for this.
1. Add a file brightness.conf at /etc/init/ with following lines
  description "Job to control brightness at startup"
  author "..."
  start on runlevel [2345]
  exec intel_backlight 14  # to set brightness to 14%
2. Changes will take effect after restart or by changing run levels.

3. You can start the job by typing:
  sudo start brightness  or
  sudo service brightness start

Wednesday, September 30, 2015

Yield Expression and Generator Function in Python

Yield expressions are only used within a generator function. Here is an example:

>>def pp():
     x = yield      #1
     yield x*x       #2
     yield x*x*x     #3
     yield x*x*x*x   #4 
     yield x*x*x*x*x   #5
     yield x*x*x*x*x*x   #6

>>g = pp()
>>next(g)     #starts the generator and executes line #1
>>g.send(5)  #sends value 5 to x at line #2 and gets the result
>>next(g)     #gets the result of next line #3
>>next(g)     #gets the result of next line #4
>>g.send(2)  #gets the result of next line #5 
3125       #cannot send a new value in the middle of execution
>>next(g)     #gets the result of next line #6
>>next(g)    #Throws StopIteration exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

Saturday, September 12, 2015

Vim AutoCompletion for Python

Installing Pydiction to enable Auto-Completion for Python in Vi (Vim) editor:
1. First install Pathogen using the System Package Manager.
2. Download vimogen int the home directory using command-line:
 git clone
3. Create .vim and .bundle directories by command-line:
 mkdir ~/.vim
 mkdir ~/.vim/bundle
4. Create file .vimogen_repos with the following content:
 echo "" > ~/.vimogen_repos
5. Run vimogen by command-line:
  ~/vimogen/   (and type 1 to install) 
  This will install pydiction in directory ~/.vim/bundle/
5. Under ~.vim do the following link:
  cd ~/.vim
  ln -s bundle/pydiction/after .
6. edit ~/.vimrc file and add the following lines:
filetype plugin on
let g:pydiction_location = '~/.vim/bundle/pydiction/complete-dict'
if has("autocmd")
  autocmd FileType python set complete+=k/path/to/pydiction iskeyword+=.,(
endif " has("autocmd")

That all you need to do. 
Now open an existing or new *.py file and check auto-completion by typing any python keyword or module partially and press tab to show the available choices.
For further reading check the following links.

Thursday, July 23, 2015

Grep between two words in string

Say from the string "Age: = 24 years", you want to extract the value 24. Grep can be used to search for a pattern between two words. Here is the grep command for that:
echo "Age: = 24 years" | grep -P -o '(?<=Age: = ).*(?= years)'

Wednesday, July 22, 2015

Using iTunes & iPhone in Virtual-Box Windows from Ubuntu Linux host

Using iTunes to access iPhone in Ubuntu is not possible but you can do it with a Windows Virtual Machine.

#1. Install Virtualbox from Oracle in Ubuntu.

#2. In Ubuntu add user to vboxusers group by this command:  
sudo gpasswd -a $USER vboxusers

#3. Connect your iPhone to the Ubuntu USB port. 

#4. Within Virtualbox install Windows-7

#5. Once installed run Windows-7 and install Guest Additions Extension Pack.

#6. Reboot the Windows-7 Virtual Machine and from the Devices menu on top, select USB and check the "Apple Inc". 

#7. Install iTunes within Windows-7. Run iTunes and it will detect your iPhone. 

Monday, July 6, 2015

Range or Sequence in Shell Script

Following is an example to print numbers 1 to 20 in a shell script. The numbers below 10 need to be printed with 2 digits like 01..09 

for i in $(seq 20) 
if [ $i -le 9 ] 
then echo 0$i
else echo $i

Tuesday, June 30, 2015

Concatenate or Convert audio or video files

In Ubuntu Linux, install the utility ffmpeg:
sudo  apt-get  install  ffmpeg

Say you want to convert all the mp3 files in a directory to a single file called output.mp3. Then do the following. 
1. cd  to the directory
2. ls  *.mp3  >  list.txt
3. ffmpeg  -f  concat  -i list.txt  -c  copy  output.mp3

Sunday, June 28, 2015

Avoid shutdown or sleep when lid is close on Ubuntu Laptop

To avoid the Ubuntu laptop from shutting down when lid is closed, open the file '/etc/systemd/logind.conf' and add the following line at the bottom.
Then restart the following service:
sudo restart systemd-logind

Tuesday, June 16, 2015

Date Command with Format

Date command in Linux shows the results as below:
#Tue Jun 16 16:18:50 EDT 2015

But if you want to display the date say in the format 16-06-15 then use the following format option with date command:
#date +"%d-%m-%y"

Choose vi editor to open with crontab

Generally "crontab -e" opens with nano editor or gives an option to choose editor when opened for the first time. 
If you want to change the editor later on, enter the command "select-editor" and choose vi. This will force crontab to use vi.

To find your ip address

To find your local IP address type the following command:
  • ip addr | grep global | grep 'inet ' | sed -e 's/\/.*//' -e 's/.*inet //'

To find your global or internet ip address, type the following command:
  • curl -w '\n'
  • curl 

Monday, June 8, 2015

To find the time response of a website

Using the command 'curl', the time response of a website or a webpage can be found. The following is an example to find the response time for the website ''

curl -s -w '\nLookup time:\t%{time_namelookup}\nConnect time:\t%{time_connect}\nPreXfer time:\t%{time_pretransfer}\nStartXfer time:\t%{time_starttransfer}\nTotal time:\t%{time_total}\n' -o /dev/null

The response will be:
Lookup time: 0.004
Connect time: 0.062
PreXfer time: 0.062
StartXfer time: 0.123
Total time: 0.248

Thursday, June 4, 2015

Python Interpreter - Removing leading dots.

Create a file with following lines in the default home directory (~):

import sys
sys.ps1 = '>>'
sys.ps2 = ''

Add the following line in .bashrc or profile file to export variable.

Wednesday, June 3, 2015

Use string variable or string to call a function

In python locals() return a dictionary representing the current local symbol table with all functions as dictionaries.
Say you have a function called  "Func()". The locals() will return a dictionary with "Func" as shown below:
{....., 'Func': <function Func at 0x7f9ff50a5268>, ...........}
Now you can the call the function 'Func()' by the calling the dictionary key as below:

Direct String Substitution:
     locals() ['Func'] ()

Variable Substitution:
    F = "Func"
    locals() ['F']

 You can also use globals() instead of locals() if you need global system table. 

If the function is part of a class then use getattr(class,"function")()

Monday, June 1, 2015

VIM HTML Documentation

How to Install and Launch VIM Documentation in HTML:

#1. First install the package vim-doc in your linux system.
#2. All the html files get installed at location /usr/share/doc/vim-doc/html/
#3. Open a browser and copy paste this link to get the main page. 

Friday, May 29, 2015

CentOS 7 Installation

CentOS 7 by default is installled as minimal server. To change this, during installation, click "SOFTWARE SELECTION" and choose the "Base Environment" and "Add-ons". 
For "Base Environment" there are several types to choose from like Gnome, KDE, Workstation, Web-Server etc.

Wednesday, May 27, 2015

Ubunty 15.04 Unity Freeze

Ubuntu 15.04 Unity freezes frequently. The solution to this problem follows:

  • Press Ctrl+Alt+F1 and get the terminal screen. Log in with password.
  • In the terminal type killall -v -9 compiz
  • Close the terminal and launch unity by pressing Ctrl+Alt+F7
Also avoid maximizing the window size to full screen. In the System Settings-->Appearance-->Behavior , For 'Shows the menus for a window' choose 'In the window's title bar'.

Tuesday, May 26, 2015

Decorators in Python

In Python Decorators are functions of functions. It is a wrapper function that wraps a regular function to modify its results.  
For example, say you have a function to capitalize the first letter of names. Now you want to add another function on top of this to include the title (Mr/Ms) depending upon the gender. This can be achieved by defining a decorator function to add the title. 

Decorator Function to add the title (Mr/Ms) based on gender:
def Title(func):
  def new(*args, **kwds):
    if kwds['gender'] == 'male': return ("Mr "+func(*args, **kwds))
    elif kwds['gender'] == 'female': return ("Ms "+func(*args, **kwds))
    else: return func(*args, **kwds)
  return new

Regular function to capitalize the first letter with decorator:
def Capitalize(name,gender=''):
  return name.title()

Now call the regular function as below:
Capitalize('john travolta',gender='male')
result >>> 'Mr John Travolta'

Capitalize('catherine zeta jones',gender='female')
result >>> 'Ms Catherine Zeta Jones'

Monday, March 23, 2015

Mount drives on startup by editing /etc/fstab

  • Say, you want to mount a NTFS drive located on '/dev/sda2' at '/mnt/nt' on startup with your username and group. 
  • First find your user-id and group-id by using the command "id" in a terminal.
  • Say your user-id and group-id are both 1000, then the line in '/etc/fstab' will be the following:
/dev/sda2 /mnt/nt    ntfs    defaults,uid=1000,gid=1000,rw    0    0

Tuesday, March 17, 2015

VirtualBox RDP

Shell Script to setup username and password for RDP connection to VirtualBox VM.

Hash=`VBoxManage internalcommands passwordhash $Pass | awk {'print $3'}`
VBoxManage setproperty vrdeauthlibrary "VBoxAuthSimple"
VBoxManage modifyvm $Proj --vrdeauthtype external
VBoxManage setextradata $Proj "VBoxAuthSimple/users/$User" $Hash

Run the script with 3 arguments - Project, Username, Password

To Remove an user from RDP login,
VBoxManage setextradata $Proj "VBoxAuthSimple/users/$User"

After setup, to connect via RDP to a VirtualMachine, use the following command:
rdesktop-vrdp remotehost:3388 -u UserName -p PassWord