For Loop UInt64 MaxValue Parallel Iteration Calculation Time

For Loop UInt64 MaxValue Parallel Iteration Calculation Time was an interesting Friday 30 Second question; if you were to iterate through a loop and you could parallelize your loop over 100 cores and each iteration took 1 nanosecond (i.e. 1 billion iterations per second) then how long would it take you to iterate over all the digits that could fit inside an UInt64?

e.g.

for (UInt64 i = 0; i < UInt64.MaxValue; i++)
{    
    ; // This operation takes 1 nanosecond and loop has no overhead
}

So this is really just a math situation. First we need to define what the value of Uint64.MaxValue is.  If we look up its value on MSDN, we know that it is a constant value of 18,446,744,073,709,551,615; that is, hexadecimal 0xFFFFFFFFFFFFFFFF.  Now at this point, it becomes common math.

This is the breakdown of how many operations will be happening per second in total across all cores.


Operations / Second / Thread = 1,000,000,000

Threads = 100

Operations / Second = 1,000,000,000 * 100 = 100,000,000,000

Now let’s apply it to the UInt64.MaxValue.

Seconds / Operation = 1 / 100,000,000,000

Total Seconds = Operations * (Seconds / Operation) = 18446744073709551615 * (1 / 100,000,000,000) = ~184467441

Minutes = 184467441/ 60 = 3074457

Hours = 3074457 / 60 = 51241

Days = 51241 / 24 = 2135

Weeks = 2135 / 7 = 305

Years = 305 / 52 = 5.86

The discussion and point that came out of this is a feature that was introduced in .Net 4.  It’s the concept of parallelizing your loops across all available processors with the Parallel.For<> loop. This will have its obvious benefits of being able to process at n times the amount of processors that are available.


Why does YUI Minify fail on char and browsers do not in JavaScript

This weeks 30 second question. Why does YUI Minify fail on char and browsers do not in JavaScript?

In JavaScript the following line of code works on all browsers that I have seen:

var char = 15;

However, the YUI minifier chokes on this line of code. Why is this? And should that line not work on browsers? i.e. why are browsers allowing that line to work?

Let’s start out with Reserved words in Javascript.  These words are words that you cannot use as variable or function names as they hold special meanings and instruction to the language.  If you haven’t guess by now, ‘char’ is a reserved keyword in JavaScript.  So in the above example we are trying to use a keyword as a variable name which causes the YUI Minify to throw a fit.  To give you an example, open up this link and plug in the following and click compress.

http://www.refresh-sf.com/yui/

var char = 15

You will be prompted with the error below.

[ERROR] 1:10:missing variable name

[ERROR] 1:0:Compilation produced 1 syntax errors.

org.mozilla.javascript.EvaluatorException: Compilation produced 1 syntax errors.
	at com.yahoo.platform.yui.compressor.YUICompressor$1.runtimeError(YUICompressor.java:154)
	at org.mozilla.javascript.Parser.parse(Parser.java:392)
	at org.mozilla.javascript.Parser.parse(Parser.java:337)
	at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:312)
	at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:533)
	at com.yahoo.platform.yui.compressor.YUICompressor.main(YUICompressor.java:131)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:585)
	at com.yahoo.platform.yui.compressor.Bootstrap.main(Bootstrap.java:21)

That answers the first part of the question, now onto the second part of the question.  Why do browsers still allow this code snippet to work?  Well, the keyword char is not actually used by the JavaScript language.  So yes it’s labeled as a reserved keyword, but it is never been used as one. Browsers run their own compilers for JavaScript and tend to have more of a lenient stance on this subject.  They want to allow as much of the JavaScript execute as they possibly can.  So since there is not a repercussion of using this keyword, the browsers don’t take it into account as an issue.  The YUI Minify is a more standards compliant engine that will follow standards, hence why it blows up when you try to use a keyword it recognizes as a word that’s off limits.


Postfix increment and decrement operators in CSharp

Postfix increment and decrement operators are great for doing quick addition and subtraction. Using your C# knowledge and not your compiler, what will the output be?

int i = 1;
string result = String.Format("{0},{1},{2}", i--, i++, i++);
Console.WriteLine(result);

Have your guess?

The output reads as follows. 1,0,1 and the last value of i is actually 2. Why is this?  We are using post operators, meaning, the compiler is going to read the value of i, then it will increment or decrement depending.  In the above example, the last i++ happens after the value of {2} is read, so it will not be seen as 2 in the console window and is not used in any execution path.  So let’s take a look at the opposite of above.

int i = 1;
string result = String.Format("{0},{1},{2}", --i, ++i, ++i);
Console.WriteLine(result);

Have your answer for this version?

The output ends up being 0,1,2 with a final value of i =2.  The reasoning is opposite of the above.  These operators will apply the increment or decrement prior to reading i.


A look at CSharp Volatile Keyword

The other day the keyword Volatile came up in a discussion and I did not know the use of it.  So I figured, why not, let’s dig into it.

The volatile keyword can be put onto a field that may be accessed my multiple threads at the same time.  The effect of applying the fields with volatile is neat.  The compiler makes numerous optimizations and for fields reordering optimizations can take place.  When you apply the volatile keyword to the field declaration, compiler optimizations will not be applied to that field.

Take a look at the example below on declaring a public variable as volatile.

 private volatile bool _Stop;

Now let’s take that and put it into an application.  [more] The following example is based off of MSDN’s example.

public class WorkerClass
{
    // Called when a thread starts
    public void Working()
    {
        while (!_Stop)
        {
            Console.WriteLine("Worker thread: working...");
        }
        Console.WriteLine("Worker thread: terminating gracefully.");
    }

    public void RequestStop()
    {
        _Stop = true;
    }

    // Keyword volatile is used as a hint to the compiler that this data
    // member is accessed by multiple threads.
    private volatile bool _Stop;
}

public class WorkerThreadExample
{
    static void Main()
    {
        // Create the worker thread object.
        WorkerClass workerObject = new WorkerClass();
        Thread workerThread = new Thread(workerObject.Working);

        // Start the worker thread.
        workerThread.Start();
        Console.WriteLine("Main thread: starting worker thread...");

        // Loop until the worker thread activates.
        while (!workerThread.IsAlive)
        {
        }

        // Put the main thread to sleep for 1 millisecond to
        // allow the worker thread to do some work.
        Thread.Sleep(1);

        // Request that the worker thread stop itself.
        workerObject.RequestStop();

        // Use the Thread.Join method to block the current thread 
        // until the object's thread terminates.
        workerThread.Join();
        Console.WriteLine("Main thread: worker thread has terminated.");

        Console.ReadLine();
    }
    // Sample output:
    // Main thread: starting worker thread...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: terminating gracefully.
    // Main thread: worker thread has terminated.
}

A lot of the explaining is done through the comments so I will save the reiteration of what has already been written.  Multithreading can cause some serious problems when they are executing at the same time.  By using the volatile keyword, it’s not causing synchronization of any parts, it’s instead telling the compiler to leave this field alone and not change the order of it.

Here is another example usage that may be a little easier on the eyes.

using System;
using System.Threading;
class Test
{
   public static int result;   
   public static volatile bool finished;
   static void Thread2() {
      result = 143;    
      finished = true; 
   }
   static void Main() {
      finished = false;
      // Run Thread2() in a new thread
      new Thread(new ThreadStart(Thread2)).Start();
      // Wait for Thread2 to signal that it has a result by setting
      // finished to true.
      for (;;) {
         if (finished) {
            Console.WriteLine("result = {0}", result);
            return;
         }
      }
   }
}

The main point to take from the second example is that with the finished variable set to volatile, it makes it impermissible for the store to result to be visible to the main thread before the store to finish.  If volatile is not used, it would be permissible for the main thread to see finished sooner and possible read the value of 0 from result.  Using volatile will ensure that this sort of ordering issues will not occur.  This does not take the place of the lock statement; it solely restricts some of the optimizations implemented by the compiler.


For Loop Using UInt16 MaxValue

A demonstration of a For Loop Using UInt16 MaxValue. How would you iterate through all of the values in an unsigned 16-bit integer?

The following two loops will not work:


for (UInt16 i = 0; i < UInt16.MaxValue; i++)
{
    // Do something
}

for (UInt16 i = 0; i <= UInt16.MaxValue; i++)
{
    // Do something
}

The first loop skips the last value; the second loop goes into an infinite loop when it rolls over.

Let’s take a look at the first loop.


for (UInt16 i = 0; i < UInt16.MaxValue; i++)
{
    // Do something
}

First we need to know what UInt16.MaxValue equates to as a value.  UInt16.MaxValue is hexadecimal 0xFFFF which is a constant value of 65535.  So when we are looking into the loop with for (UInt16 i = 0; i < UInt16.MaxValue; i++) the last iteration will not happen because we would need an overflow value of 65536.  However, since UInt16.MaxValue is a constant value of 65535, the last value causes the loop to exit before the last Do Something is completed.

Let’s take a look at the second loop.

for (UInt16 i = 0; i <= UInt16.MaxValue; i++)
{
    // Do something
}

The problem we are seeing here is an infinite loop gets created.  This again takes us to needing to understand how UInt16.MaxValue works.  As we said, UInt16.MaxValue is the hexadecimal value of 0xFFFF.  So if you look at this loop if will actually go through and complete the last iteration at 65535.  However, in terms of this hexadecimal value, when you add 1 to it after the last iteration if wraps around to 0 again. Hence, our infinite loop problem.

Solution? Use a do/while loop.

ushort i = 0;
do
{
    // do something
}
 while(i++ < UInt16.MaxValue);

This is close to the first loop in our question, but it will cause the Do Something to iterate all the way through before it does a check on the UInt16 value.

Here it is as a test console app to confirm all the above from Guy Ellis.


static void Main(string[] args){
    UInt16 i = 0;
    do    {        if (i == UInt16.MinValue)
        {
            Console.WriteLine("MinValue");
        }
        if (i == UInt16.MaxValue)
        {
            Console.WriteLine("MaxValue");
        }
    } while (i++ < UInt16.MaxValue);
    Console.WriteLine("Enter to finish...");
    Console.ReadLine();}


StackOverflow Profile