Thursday, February 26, 2009

How to get the elapsed time in millisecs

Finding an elapsed time of a function/API/method will help you to understand its performance and the most of our manager/management will hails u if you give them a nice performance graph/chart of an application :)

My Approach:
You can use gettimeofday at the start and end of your method and then the difference the two will give the elapsed time .. You'll get a structure like the one below:


struct timeval {
time_t tv_sec; /* in secs */
suseconds_t tv_usec; /* in Microseconds */
};


Code snippet:


#include
#include
#include
int main()
{
struct timeval start, end;
long mtime, seconds, useconds;

// Get the start time
gettimeofday(&start, NULL);

// Here you go with your method call
usleep(2000);

// note the end time
gettimeofday(&end, NULL);

seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;

mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

printf("Elapsed time: %ld milliseconds\n", mtime);

return 0;
}


Wednesday, February 25, 2009

Python: Human readable time span given total secs

Problem:

Function takes an amount of time in seconds and returns a human readable time span.

Input: 14723 (in secs)
Output : 4h 5m 23s

Suffixes used:

y - year
w - week
d - days
h - hours
m - min
s - sec

Code:


#!/usr/bin/env python
def elapsed_time (seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
"""
Takes an amount of seconds and turns it into a human-readable amount of time.
"""
# the formatted time string to be returned
time = []

# the pieces of time to iterate over (days, hours, minutes, etc)
# - the first piece in each tuple is the suffix (d, h, w)
# - the second piece is the length in seconds (a day is 60s * 60m * 24h)
parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
(suffixes[1], 60 * 60 * 24 * 7),
(suffixes[2], 60 * 60 * 24),
(suffixes[3], 60 * 60),
(suffixes[4], 60),
(suffixes[5], 1)]

# for each time piece, grab the value and remaining seconds, and add it to
# the time string
for suffix, length in parts:
value = seconds / length
if value > 0:
seconds = seconds % length
time.append('%s%s' % (str(value),
(suffix, (suffix, suffix + 's')[value > 1])[add_s]))
if seconds < 1:
break

return separator.join(time)

if __name__ == '__main__':
# 2 years, 1 week, 6 days, 2 hours, 59 minutes, 23 seconds
# 2y 1w 6d 2h 59m 23s
seconds = (60 * 60 * 24 * 7 * 52 * 2) + (60 * 60 * 24 * 7 * 1) + (60 * 60 * 24 * 6) + (60 * 60 * 2) + (60 * 59) + (1 * 23)
print elapsed_time(seconds)
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'])
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True)
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True, separator=', ')



Output:

[10:13:34 gmuniyan@lnl43a-3102] /home/gmuniyan/python>./elapsedTime.py
2y 1w 6d 2h 59m 23s
2 year 1 week 6 day 2 hour 59 minute 23 second
2 years 1 week 6 days 2 hours 59 minutes 23 seconds
2 years, 1 week, 6 days, 2 hours, 59 minutes, 23 seconds

Honor: Original Post

Tuesday, February 24, 2009

Running a cmd from bash script

Problem:

There are many situations in which you may want to run different command in your shell script depending on requirements and circumstances.

There are two approaches we can take from here on.

Approach #1:

Use either case statement or if..elif..else For example:



#!/bin/bash
if [ this -eq that ];then
command1
else
command2
fi



Approach #2:

BASH allows you to assign/store a command in a built-in variable called CMD. Build your command in this variable and execute $CMD.



#!/bin/bash
[ this -eq that ] && CMD=”/bin/ls” || CMD="/bin/date";
eval $CMD;



This is a very simple example and this approach is very much generic if you want to have a generic function to execute all the commands. For example:



#!/bin/bash

execute() {
# $1 holds the arg to this function
CMD="$1";
eval $CMD;
}

## Here is your main function

if [ this -eq that]
then
execute "/bin/ls | wc -l";
else
execute "/bin/ls";
fi



NOTE: eval is required when you use "|" or redirection of cmd output.

Happy hacking :) !!

Monday, February 23, 2009

Python: Processing cmd line args

Next thing that you might be interested to learn after the historic "Hello World" program is to know how to process the cmd line arguments.

Method #1: Using sys:


#! /usr/bin/python

import sys;

if __name__ == "__main__":
for args in sys.argv:
print args;




Output:

# cmdLine.py 1 2 3 4
cmdLine.py
1
2
3
4

Python: Hello World

This is my first post against Python, watchout for more to come soon ...

Python way of saying "Hello world" :)


#!/usr/bin/env python

## In Python each module will have a name associated with it
## And here is the main module

if __name__ == "__main__":
print "Hello World";

Sunday, February 01, 2009

Show that 2^n is O(n!)

This is an interview question from MS.

Answer:

n! = 2*3*...*n >= 2*2*...*2 = 2^(n-1)

Since 2^n <= 2*n! for all n, we have that 2^n = O(n!).