Saturday, April 20, 2013

C++ COW Craziness

Note: This isn't one of those Linus'ish articles that bitches about C++. I like C++ and I would just like to point out one of the many nuances in the language that could affect the performance of your program without your knowledge.


C++ STL's string class promises Copy-on-write. What that means is that, you can make as many copies of the string, but the actual memory duplication will happen only when one of the strings are actually written to (i.e.) no memory duplication will be made for copies that are made for pure reads. Or atleast that's what I thought, until I discovered today that, if you use the [ ] operator on the string, you rig the COW functionality of it forever. It is something that you normally don't do, but doing so could cost you a lot of performance. Let's run through an example.
string s1(1024 * 1024 * 16, 'g');
for(int i = 0; i < 1000; i++) {
  string s2 = s1;
}
This runs in 19 milliseconds. That's because (obviously) there are no actual copies made. Just 1000 pointers being created to the existing 16 megabytes of data. Now, lets try modifiying the copied string.
string s1(1024 * 1024 * 16, 'g');
for(int i = 0; i < 1000; i++) {
  string s2 = s1;
  s2[0] = 'v';
}
This runs in 4.3 seconds. That's right, from 19 milliseconds to 4.3 seconds for making 1000 actual copies of 16 MB of data. This is the expected behavior, a copy is done when you try to write to it. Next comes the weird part, consider the following code:
string s1(1024 * 1024 * 16, 'g');
for(int i = 0; i < 1000; i++) {
  string s2 = s1;
  s2[0];
}
Guess how much time this should take? Intuitively it seems like this should hit the COW fast path (i.e.) no actual copies, because there is no "write" here. This takes 4.3 seconds too! The problem behind the [ ] operator is that, you can easily stash away a pointer to some portion of the string and modify it later thereby screwing up the state. So, it is impossible to perform COW once you use the [ ] operator on a string. The following snippet illustrates this:
string s1("hello");
char *p = &s1[2];
string s2 = s1;
*p = 'v';
You see what happened there? You stashed away a pointer to the middle of the string and then tried to change it later after the copy. This is sort of an indirect write, and there is no way for the compiler to determine this. So, the moment is sees the [ ] operator, it removes the COW functionality for that string. One way to do such a read without rigging the COW functionality is to do a crazy cast like this:
string s1(1024 * 1024 * 16, 'g');
const_cast<const string &>(s1)[0];
for(int i = 0; i < 1000; i++) {
  string s2 = s1;
}
This snippet takes the fast COW path and runs in 20 milliseconds. The takeaway from this article is that, do not use the [ ] (or the .at()) operator on strings, especially large string that could be copied later on. Even though you think you're doing an harmless read, you are rigging the COW functionality of that string forever. You are paying the price for that pointer you stashed away (or may be even released long back) without knowing.

 -Vignesh

Tuesday, February 26, 2013

The Last One by Myself!

Before you start reading, I really would like to warn you: Stop, Do not read. What follows is utter crap.

It has been almost 5 years now since i fell in love with this amazing girl. It’s almost time now. I am literally counting the last few days of my bachelor life. The 7 and odd years that i have known her has just swung by very fast. It just seems like yesterday that I was a small school kid. I honestly can’t remember how college life went on so fast. Here I am now, sitting in a totally different part of the world, still unable to believe that I am actually here.

When I look back at the past 7 and odd years, there are various wonderful moments which I would say have made my life what it is now. Not to brag, but not many people in life get almost everything they want, especially at such an early point in life. I am indeed one of the lucky ones. I am surprised at so many things that I do these days. It just seems like yesterday (literally like yesterday) that i went around nagging people for career advice. Yet here I am today, talking to many of my friends about building their career, etc. I really am surprised at the way I have turned out.

I am in this state where i ponder upon looking for words to express how my life has turned around to what it is now. There has been unexpected twists and surprises, expected happiness and so many other feelings which words cannot describe.

If I sit back for a moment and think about why I am writing this post, I honestly have no clue. I just felt like I should write something that will forever remain as the last post I ever wrote as a bachelor. Not that it is a big feat or anything, but blogging was something which, despite many resolutions and swearings, i could not keep up with. So, not to feel bad about myself that I hardly write anything these days, I started out writing this particularly pointless post.

I am flying out to India tomorrow. It’s gonna be the most #epic trip of my life. Loads of things to look forward to. Girl of my dreams, getting together with her. Life is fun. Hopefully I write something meaningful sometime soon (of course after I am back from the India trip).

-Vignesh

Wednesday, December 12, 2012

Life on the Pacific Coast!

Disclaimer: These are my impressions. They're not facts, they're my impressions, so they can't be argued with. Also, it's quite a lengthy post! With that out of the way let’s begin.

It has been close to 3 months since i moved to a totally different part of the world. The experience so far has been mind blowing if anything. Dream job, wonderful location, awesome co-workers and above all, amazing culture of people. I have been taking notes since the past three months and am posting my observations about this part of the world as i have seen it in this short period.


First Picture after I landed in the US

Human involvement == Expensive
Anything involving one to one human attention for a significant amount of time will be significantly expensive. For instance, you can reach from place to another in a bus for $2 but the same might cost anywhere between $20 and $100 in a cab. A loaf of bread costs around $3 whereas a bread toaster costs $13. This is because bread loafs are perishable and requires constant human interaction for replacing it, probably on a daily basis. Whereas the toaster will be mass manufactured by a machine in thousands and requires the least human interaction. The main upside to this is that people are very hands on. They usually assemble their own furniture and so on. Hiring a human on a hourly basis is *much more* expensive than buying the required tools and doing the job yourself.

Public transport == Longer
In India, if you can cover a certain distance by car in 15 minutes, you can usually cover that in a public bus in 30 to 45 minutes. Here, if you take the bus for the same distance, it could take anywhere between 60 to 90 minutes (depending on whether you have direct bus access or not). You can see this for yourself as to how long it takes from a location to SJC airport by car (15 mins) and by public bus (85 mins). The reason behind this is quite straightforward. In the US, traffic is in two extremes: you either take the freeway which has no signals whatsoever or you take some internal road with overwhelming signals and other obstructions. Cars take the freeway and public buses don’t, hence the significant time difference.

CTM!
Can anybody guess what CTM stands for? Ok now can anybody guess what this is doing in this post? I’m unsure of the reason, but whenever people here refer to Indian food, CTM is the de facto scale of reference. They tend to compare the spiciness of other stuff with CTM as the base scale. Also, people who have never been to India usually differentiate between North and South India as bread eating and rice eating parts of India.





New term for Public Wifi
When i was back in India, I always used to wonder what’s the point in having any wifi only tablet, or any other wifi only device for that matter. Now I understand why it totally makes sense. All the public places usually have free wifi. Especially since i live in mountain view, i enjoy free city wide wifi provided by Google. Also, Starbucks wifi is the most common example of public wifi. Starbucks is a coffee shop which exists on almost every street and usually all Starbucks shop have free wifi, thereby extends that almost all streets have free wifi.

New notion of City
The notion of a “city” is very different when compared to what it means in India. Cities in the US are small, very very small when compared to cities in India. For instance, the distance between Mountain View and San Francisco airport is 25 miles (~40 kilometers). In India, if you drive 40 kilometers from a place, it is very likely that you’ll still be in the same city. Whereas there are some 5 to 7 cities between Mountain View and San Francisco. They are that small. On an average, if you drive about 6 to 7 miles from any city, you’ll definitely be in some other city. There’s another level of granularity known as counties. County sizes here match with city sizes in India (size, not the population!).

Meat is De Facto
I am not sure if it seems so because i am a vegetarian, but in general what i have noticed is that meat is the de facto ingredient for preparing any sort of food. Even soups by default have a meat based stock. You will have to specifically ask for the restaurant guy for food without meat and seafood (for which the choices will be usually limited in a normal restaurant). But there are a lot of places in the bay area where one can get very nice vegetarian/vegan food. By the way, McDonalds in the US does not have any vegetarian dishes which makes me realize how much they have customized their menus for their Indian version (there’s McAloo Tikki!). Tofu is the usual vegetarian replacement for any meat.

Go Karting
Car driving in this country is a joke. Yes, the traffic is high speed, but apart from that there’s no thrill in driving. Majority of the vehicles have automatic transmission (which means that one hand and one leg is always free while driving). The only challenge is to learn the lane discipline, but that’s a matter of very short time. Once you learn the rules, driving is a piece of cake. If you have ever done Go Karting in India, you can drive real cars here. That being said, rules have to be followed here even while driving in a small road where there is no traffic whatsoever. Cars are the default mode of transport, there are a very very small number of motorcycles (bike == bicycle here, hence the term motorcycle). Motorcycles are more of an enthusiasm here than a mode of transport. They cost about 4 times as a car and hence very rarely found on roads (Edit: I realized this was an exaggeration. Depending on the type of car and type of motorcycle the prices vary. But the general idea is that motorcycles aren't intended as a primary mean of transport. They are more of a fun thing).



US-101

Water, Coke and Beer
Almost all these three cost the same, in the sense that the difference isn’t significant as it is in India. You can get water and coke for the same price and beer will cost a little more. Again like meat, beer is very commonplace. All shops usually sell beer and there are bars in almost every major places in the city.

Pedestrians and Bicyclists
Contradicting Indian behavior, pedestrians and bicyclists (bikers) are given priority at any intersection. Vehicles taking free right turns or passing an intersection without signal always come to a complete halt to look out for pedestrians and bikers. Even if the pedestrian or biker is a little away from the intersection, the vehicles usually wait for them to pass. This is religiously followed by all vehicle drivers irrespective of the type of powered vehicle they drive.

Silicon Valley == Epitome of Technology
Technology is used almost everywhere, it is more or less ubiquitous. One of the main reasons for this is availability of internet everywhere (as i mentioned earlier 1Mbps internet is free in mountain view). Buses and trains are high tech and have systems for ticketing that logically make a lot of sense. For instance, a single ride in a bus costs $2 and a day pass costs $6. You can use a prepaid smart card and the system is actually smart enough to charge you not more than $6 for the rides you take in any 24 hour period. Debit card cash back is really an awesome system. I don’t see any reasons why they don’t have that in India. It is a true win-win.



San Antonio Caltrain Station

Cash? Why not card?
Cash transactions are very very rare. It’s been three months and i still have the cash that i bought along with me when i came from India. Every shop, as in every single shop, accept credit/debit cards. So there is no necessity carry a wallet. I just carry my card in the pocket along with the phone. There are even mobile phone cases with credit card holders.

Differences in words
There is a lot of difference between American english and Indian english, many of which i learnt only after getting here. Glaring ones include: 1) Ground floor is mentioned as First floor here, First is Second and so on. 2) Capsicum is called Green pepper (the guy from subway stared at me when i said capsicum). 3) Bill is called Check and Cash is called Bill (the paper note). There are loads of such word differences.

Numbers can be Deceiving
Not following the metric system is a pain in the ass. The distance unit is particularly very deceiving since you look at 1.3 miles and start walking, whereas walking 2 and odd kilometers is really difficult (when comparing the distances which i used to walk in India). 



Note: Image copied from Facebook

More than all this, the best part about this country is its people. They are friendly by heart. Even strangers greet each other. The bus driver tells you to have a nice rest of your day when you get out of the bus. The person whom you held the door for tells thanks. To reiterate, the best part for me so far has been the People!

Such has been my experience in this country so far. I am enjoying every moment of it. It has given me a whole new view of how life can be, since all this is a sudden surprise (something i never constantly dreamt of). Maybe i’ll do another blog post after 6 months describing the views then.

Good grief, my blog is not dead. I will definitely write more soon!

-Vignesh

Thursday, September 20, 2012

On Leaving India!

Warning: This is a random rant. And some of you may not be ok with the attitude of this rant.

It's almost time and I'm all set to leave India for the first time and it is probably for my good. It is a bit ironic that of all people I've been the one chosen to leave the country at such an early stage of life. As my email id goes, few months back, i had the least idea that i would go out of the country and that too as a long term business. Nevertheless, it's hard to turn down when your lifelong dream calls you to make a choice between itself and the country you love.

I've been known among my friends and family to often pass off niche comments whenever I'm asked about going to another country for a long term. And truly, by heart, even now i cannot think of settling down permanently in country other than India. So I've been in extremely mixed emotions about this. I'm not saying it was a hard choice to make, the choice i had to make was damn easy. But somewhere in the corner of the heart it pricks a little bit as i am actually about to go through with it. Nevertheless I'm damn excited on this new phase of my life. It has really moved very fast so far.

As most of you might already know, I'm now formally engaged to my long term girl friend Gayathri. She is the most amazing human being I've ever met in my life. So naturally, this adds even more excitement to my trip given that marriage is around the corner. In a way, I'm more excited about coming back here for marriage than about going there and taking up my first job.

Personally this journey is a big step for me as I've never gone beyond South India most of my life. Bangalore and Hyderabad have been my borders except for one Delhi trip during college. So I'm half excited and half scared to face the new geography, new culture and what not. Everything is a bit overwhelming, I'm gonna be staying right across the road from Stanford for my first few weeks there.

Off late the only question I'm being asked by everyone is "Are you gonna permanently settle down in the US?". I really don't know the answer for this question. All my life i never thought I'd set foot in another country for a long time. But here i am all excited about how things have turned over in a few months. So I'm not really in the mindset of planning for the long term. Deep down the heart i wish to be back in India sometime in the future.

I'll conclude this almost pointless rant by saying i will miss a lot of things about Indian lifestyle but I'm looking forward to the most important phase of my life and I'm not a least bit sad about it not being in India.

And hey, I'm getting married on March 4, 2013 in Chennai. I will surely invite every one of you personally later, just book your calendar for that date right away :-)

-Vignesh

Wednesday, July 11, 2012

Serverless Downloads - HTML5 Awesomeness!

HTML5 brings an awesome feature known as client downloads. At first glance, the term "serverless downloads" may sound oxymoronic, but it sure makes a lot of sense. In the HTML5 era, we write a lot of thick clients. All the day to day web apps which we use are damn thick (Gmail, Facebook, etc.). So in the context of thick clients, serverless downloads make a lot of sense.



Content-Disposition HTTP Header

On the web 2.0 days, when you wanted to force a browser to download a file to disk rather than displaying it (especially if the file is of some format which the browser is capable of rendering), you used to set the Content-disposition header in the HTTP response.
Content-Disposition: attachment; filename="sample.txt";
There is no way for the browser to let the user download the file without contacting the server, even if the contents of the file were to be generated totally on the client side.


The Problem

This is old school. These days there are lot of web apps where you create the data on the app itself. For example, consider Google Docs, you create all sorts of documents on the web. Every time you click the download button, the data is sent to the server and the same data comes back along with required filetype's additions and you see the download dialog box.

This step seems too radical and unnecessary. Given how thick the clients are these days, it is atrocious to send some data to the server and get back the same data as a file from the server. The same holds for all sorts of web based photo editing apps, etc.


The Solution - "download" attribute

Now with HTML5 it is possible to generate a file on the client side and make the user download it without contacting the server at all. The simple addition of "download" attribute to the anchor(a) tag will tell the browser to download the content present in the "href" attribute rather than navigating it. Now, this can be combined with a "blob:" or a base64 encoded data url to create a file and download it, all on the client side.

I have put up a demo where you can enter text into a field and then download it as a pdf.

Demo: http://garage.foamsnet.com/static/pdf.html
Image Courtesy: http://www.html5rocks.com

-Vignesh

Saturday, June 23, 2012

Convert your keyboard into an Android game controller!

I have been gifted with a new android phone. It's the big G branded Galaxy Nexus. Its blazingly fast and awesome to use (especially after years of HTC Wildfire usage). Right from day one, i have been really addicted to this game called Temple Runner which wasn't compatible with my old phone.

The game is very straightforward to play and it involves only 4 different operations. Swipe up, left, right and down. Coming from a strong keyboard background, I was never 100% comfortable with touch interfaces as i was with keyboard. And these 4 operations sounded analogous to the accelerate, brake and turn operations while playing a racing game in the computer keyboard.

That got me thinking, is there a way to make the computer keyboard into a game controller for my Android phone? Turns out its fairly straightforward. In this post i'll explain exactly how to do that.

Ingredients
  • Android phone (obviously)
  • USB cable connected in debugging mode
  • Android SDK installed
  • Very very basic python english
There's a tool named monkeyrunner which enables us to send operations from the computer to the phone via a very simple Python API (monkeyrunner tool is a part of Android SDK). A sample code for a controller would look like this:

Code until line 7 is fairly straightforward to understand. The only thing that i would like to explain here is the device object. It is an object of the MonkeyDevice class. This class has all the API methods that you need to use in order to simulate the operations. For example, device.touch(100, 200, MonkeyDevice.DOWN_AND_UP) will simulate a touch event at co-ordinate 100, 200 (with the origin being top left). As simple as that!

You can find the detailed documentation of the monkey device class to know about other methods like drag, type, etc.

The full code which i used for playing Temple Run game is given below:


One point to note is that, the sys.stdin.read(1) line will read one character and wait for the enter key to be pressed. This could be annoying given that you are writing a game controller. In order to avoid the enter key press, if you are on linux run "stty raw" before running this script and if on windows use the getch function in msvcrt module.

-Vignesh

Friday, May 25, 2012

I'm Feeling Lucky!

I have completed my college life. No more exams, no more results, no more bunking first half and sleeping and lots of other things will be no more. At this point, I want to take some time out, share the experience of my amazing roller coaster ride and thank the people who mattered and have helped me get where I am today (and where I will be in a few months :-P).

The Dream

Just like every computer science student, I had a dream too. My dream started along a bit early. Right from my school days, I had two role models. I had only one dream. I found a few 6 year old messages in my gtalk log where i was cribbing to my friends about my dream of working at my dream company at its headquarters.

The Start

I got through a really good job during my on-campus placements. It is at this point most people get carried away, but somehow i managed to not fall into that trap and thereby miss my dream. I chose to do my final semester internship in another company so that I will have bandwidth to explore other options. Btw, the workplace where I am doing my internship is awesome (this place is so awesome that I just can't stop boasting about it whenever I talk of internships).


Ok coming back to the topic, naturally the first step was to prepare for other companies' interviews. I started doing that and decided to apply to a company by end of March. Thankfully, one of my friends knew a person there who could refer me and get me an interview (btw, my friend happens to be a really wonderful human being who has helped me whole heartedly whenever i needed any help. He also happens to be my college senior and i am heavily indebted to him!). Off went my resume into the company and i got an automated "thank you for your interest in us" email.

The Phone Call

Then the recruiter called me and was ready to set me up with interviews beginning with a phone screening. I was told I would get a call by 11 AM. The interviewer had some issues in dialing in my number so it got delayed by 10 minutes. One of the worst 600 seconds of my life where I was tensed to the core. Once the interviewer called me, time flew off. Einstein was right.

I felt quite confident. Eventhough i didn't nail the interview, I felt it was far away from being tagged along a tweet as #pathetic. Few days later, I got an email from my recruiter stating that I have cleared the phone screening and will have to visit their office in Hyderabad for on site interviews.

The Visit

I was plagued with sickness and was in a severe low health for a few days before the interview. They flew me from Chennai to Hyderabad on the evening before the interview. I have been informed that I would be picked up by a cab as soon as I landed at Hyderabad. That was the first "awe" moment of the trip. The cab driver was standing at the arrival lounge with a placard that had my name.


I couldn't have dinner that night, couldn't have breakfast on the day of the interview. Somehow i reached the office. The first thing I noticed was the sheer enormity of the Hyderabad office. It was just too good.

Thankfully Air India was flying that day!
Once I reached the office, I had to have a sticker with my name printed on it (a temporary id card sorta thing). Since it wouldn't stick to my t shirt, i had to stick it around my arm like a watch!



And then there were 6!

Then started the interview process. There were 6 rounds each comprising of 45 minutes to one hour. I had a lunch break in between for half hour and eventhough i couldn't eat much (because of my illness), i was totally mesmerized by the food court that they had. The interviews were over around 6 o clock in the evening and I came back to Chennai the same night. It was a long day and i was totally down with illness at the night.

The Wait

Next came the worst part, waiting for the results. I don't know what to write in this column, but there a few things and people that helped me overcome this strenuous period. My work at internship gave me some distractions but night times were a nightmare where I barely slept for 2 or 3 hours.

The Surprise

Then came the call on 17th May, stating that I have gotten through and that I will be intimated about the work location in a day or two. I was wonderstuck, I had no words to describe what it meant to me. I mean, it was my dream ever since from when I was at school. Fortunately, I was with the people I love when the call came and I could not have been more happier.

As it turns out, the call on May 17th wasn't the happiest moment in my life. That came a few days after, when I received my offer letter. It was a totally unexpected freaking surprise. My salary was mentioned in US dollars. I was searching the letter to know my work location (as I was most eager to know whether the work location would be Bangalore or Hyderabad). When I found it, my heart just froze, I mean, it just froze. It was my dream location. It was what I dreamed about in my school days. It was whose pictures I posted in Orkut years back when it was my dream.

It was a DREAM COME TRUE !

The People

None of this would have happened if not for the really supportive people around me. I have an amazing set of F.R.I.E.N.D.S from college and school. I really owe them for all their support over the past howmanyever years I have known them.

Another bunch of people whom I really owe a lot are my friends in twitter. It was one of the main reasons why I was able to achieve my dreams. Every discussion (the technical ones) I had in twitter had been a value addition to me. When I think of it, few people come to my mind immediately. Thanks a lot guys, eventhough we've hardly met in person, you are a vital part of my life.

Thanks are due to my parents who have been alongside me for every single decision I took in my life. They trusted me totally and I hope I have justified that trust to a certain extent now.

Apart from them, I sincerely thank all of you who have been a part of my life over the past 22 years. Without you people, I will not be where I am today.

Conclusion

I am joining my first full time job in a few months. I am living in dreams when i think of the fact that i am going to be working in the same place where people like Prabhakar Raghavan, Matt CuttsGuido van RossumJoshua BlochRobert Love (and not to mention Larry Page and Sergey Brin) work. My life cannot be more close to perfect than it is now. Once again, I sincerely thank each and every one of you!


I'm Feeling Lucky!

-Vignesh

P.S.: I have not mentioned about one very important person in this post. That is completely intentional and the reason for that being lack of words to describe what that person means to me. :-)