<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dean on Medium]]></title>
        <description><![CDATA[Stories by Dean on Medium]]></description>
        <link>https://medium.com/@d34nm?source=rss-5d6c9fee8a79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oYAmAdqVabgfL6F6Hg9q7w.jpeg</url>
            <title>Stories by Dean on Medium</title>
            <link>https://medium.com/@d34nm?source=rss-5d6c9fee8a79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:03:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@d34nm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[My “white” noise]]></title>
            <link>https://medium.com/@d34nm/my-white-noise-9682573c51f5?source=rss-5d6c9fee8a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/9682573c51f5</guid>
            <category><![CDATA[podcast]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Dean]]></dc:creator>
            <pubDate>Sun, 13 May 2018 23:44:08 GMT</pubDate>
            <atom:updated>2018-05-14T16:35:38.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTbLXkgXFm3bkfIkM006Yg.png" /></figure><p>This post will be on a shorter side. I wanted to share my “white” noise.</p><p>One of the best ways to follow and keep up with advances in our chosen field is podcasts. It is an easy and fun way to see how other people think about the same questions that you may have. I also discovered many fun new things just listening some podcast. This knowledge is out there. Free.</p><p>The material from this list I use to keep myself informed and up to date. When I’m working I also like to use it as a white noise. It helps me block office chatter with some useful information. I can’t say that I will be 100% focused on the talk, but when my brain detects some interesting “keywords”, I will trigger and pay more attention.</p><p>So the following list is my favorites podcasts and channels.</p><h3><a href="https://www.codingblocks.net/">Coding Blocks</a></h3><h3><a href="https://www.dotnetrocks.com/">.NET Rocks!</a></h3><h3><a href="https://www.hanselminutes.com/">Hanselminutes</a></h3><h3><a href="https://www.programmingthrowdown.com/">Programming Throwdown</a></h3><h3><a href="https://twit.tv/shows/floss-weekly">FLOSS Weekly</a></h3><h3><a href="http://thisdeveloperslife.com/">This Developer’s Life</a></h3><h3><a href="https://itunes.apple.com/us/podcast/artificial-intelligence-in-industry-with-dan-faggella/id670771965?mt=2">Artificial Intelligence in Industry</a></h3><h3><a href="https://softwareengineeringdaily.com/">Software Engineering Daily</a></h3><h3><a href="http://www.se-radio.net/">Software Engineering Radio</a></h3><h3><a href="https://blog.ycombinator.com/category/podcast/">Y Combinator</a></h3><h3>That is all folks… For now</h3><p>When I started going through the list of my subscriptions I was quite surprised by the number of them. So I decided to stop at some time and decided on just some of them that I am naming here. There will be part two of this post so stay tuned for that.</p><p>There are many podcasts that I’m following and the list above just highlights the one which I listen regularly. The above list is to which I keep coming back week after week. There are many out there and it is hard to cram everything into one post. I even, during the writing of this post, found out that I need to catch up with some of them. There were some really interesting topics that I am looking forward to hearing their opinion about it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9682573c51f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adventures with data types in the IL]]></title>
            <link>https://medium.com/@d34nm/adventures-with-data-types-in-the-il-fefe94e95606?source=rss-5d6c9fee8a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/fefe94e95606</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ilasm]]></category>
            <category><![CDATA[il]]></category>
            <dc:creator><![CDATA[Dean]]></dc:creator>
            <pubDate>Sun, 13 May 2018 23:43:23 GMT</pubDate>
            <atom:updated>2018-05-14T16:40:49.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9z3NmMN0h0lB79sfaM5EXQ.png" /></figure><p>As I mentioned in my <a href="https://medium.com/@milojevicdean/adventures-with-il-4ac79e763fc6">previous post</a>, I will be dealing with IL in a series of articles. In this one, I would like to work on a data types and variable declaration in the IL. I am well aware that this is not a complex problem to tackle, but it is important to know what are the underlying data types in the IL.</p><p>To be honest, there is no big difference between the naming in the C# data types and IL ones. The second part of this post will focus on the variable declaration. This is a big part of any language, so for me, it is a good starting point. Here I will write about the variable declaration. Especially, this is where we will encounter a little bit of difference between C# and IL.</p><p>So, lets first kick off with the data types and their contra-parts in the C#.</p><h3>To Bool or not to Boolean</h3><p>In this chapter, I will be taking a look at the data types that exist in the ILAsm. I don’t think that there will be anything that you will find strange. Yeah, some naming may be different, but when you understand the corresponding data type in the C# it will make more sense.</p><p>Ok, the following table will show the .NET types and how they are represented in the ILAsml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*so6E8-Nd2jnXiQsc." /></figure><p>As you can see, nothing complicated when you put in the comparison table. We can also notice that not every type is present on all other platforms. Now let me drop something on you that can play important role in your code.</p><p>CLS stands for the Common Language Specification. From the name, we can already maybe see where this is going. But even so, what it means to be CLS compliant boils down to this: Make sure that your code (dll or a framework) can be used/executed by any CLR language. This means that if I write CLS compliant code in C# it should be possible to use the same piece of code in F#. So now I hope that my comment, that from a name we can see where this is going, makes more sense. It is a pretty simple concept. Simple and yet powerful. Don’t get me wrong. This is not a new concept but is one of the better implementations that I saw.</p><p>On the other hand, it is really hard to find the need to make your libraries/frameworks, in the same company/project, CLS compliant. If you wish to push something on a NuGet server, so everyone can use it, then I would seriously consider it.</p><p>But what if I need some data type that is not defined here? Well, if we remember the basis of the anything in the .NET is Object. Based on that, we can assume that we can use other data types in ILAsm. And we would be correct. You just need to be more explicit when writing your code, but you can do this without any problems.</p><p>Ok, back to the topic. Now that we saw the data types we can continue with the second part of this post. Variable declaration.</p><h3>Variables, you can do that?</h3><p>The ILAsm is not an exception to all other languages that in some way or other have a possibility to declare the variables. The syntax is a little bit different than in the OOP languages, but it is to be expected. Now, let us try to write our first piece of software that declares and uses a local variable. This example will be pretty simple, we will declare two variables (of type string) and print “Hello World”.</p><pre>.assembly extern mscorlib {}</pre><pre>.assembly Example<br>{<br>  .ver 1:0:1:0<br>}<br>.module example.exe</pre><pre>.method static void main() cil managed<br>{<br>  .entrypoint<br>  <br>	.locals init (string, string)</pre><pre>	ldstr &quot;Hello &quot;<br>	stloc.0</pre><pre>	ldstr &quot;World&quot;<br>	stloc.1</pre><pre>	ldloc.0<br>	call void [mscorlib]System.Console::Write(string)</pre><pre>	ldloc.1<br>	call void [mscorlib]System.Console::Write(string)</pre><pre>	ret<br>}</pre><p>Here it is. Nothing complicated. The directive .locals is used to declare the variables. This needs to be done before the variable is used (I know, ground-breaking discovery). In the example above, we declared two variables of type string. After that, we use our old directive to load the first part of the string to be printed out. The variables in the ILAsm can be accessed by the index. The directives stloc.0/ldloc.0 and stloc.1/ldloc.1 do just that.</p><h3>Closing act</h3><p>Now you have some idea about the data types and variables in IL. To be honest, nothing complicated. But for playing with more complex examples, it is needed. In the next chapter on the topic of the IL, I will be dealing with the branching in the IL. Until then, have fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fefe94e95606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adventures with IL]]></title>
            <link>https://medium.com/@d34nm/adventures-with-il-4ac79e763fc6?source=rss-5d6c9fee8a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ac79e763fc6</guid>
            <category><![CDATA[ilasm]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[il]]></category>
            <dc:creator><![CDATA[Dean]]></dc:creator>
            <pubDate>Sun, 13 May 2018 23:41:33 GMT</pubDate>
            <atom:updated>2018-05-14T16:41:36.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUCtwSAXgFqxrC0pMlLG_Q.png" /></figure><p>One of the most fun things for me in the .NET is to look at the compiled IL code. IL stands for <strong>Intermediate Language</strong>. Long story short, whenever you write a piece of the code in .NET at the end your compiler will boil it down to IL.</p><p>This started originally as <em>MSIL</em> (Microsoft Intermediate Language). Now is more known as <em>CIL</em> (Common Intermediate Language), to fit the ecosystem that is Microsoft creating around the .NET. If you’re asking yourself why would you need to know more about IL is simple. It will make you a better developer. You will understand the “syntactic” sugar that abstracts a lot from you. You will see clear differences between the “for” and “foreach” and a lot more fun things. The IL is the lowest level of the programming language that is readable.</p><p>If you are up to the task you can even write a simple application using IL. To make a clarification, there are two flavors of IL. The binary representation of IL (which is what everyone is talking about when mentioning IL). The second one is <em>IL Assembly</em>. My first attempt, years ago, returned me to my college days and couple of courses where I was programming in AL (<em>Assembly language</em>). If you never saw an AL it will look really strange to you. Don’t get discouraged and try to understand it. When you grasp the basics, everything will start to make more sense.</p><p>This is not something that everyone is interested in. So if you just want to see what your code looks like in IL version, there are tools that can help you with this. If nothing else, just for educational purposes and to maybe improve yourself as a developer. For me, it was helpful to understand the differences between different approaches to the same problem. As well optimizations that compiler will do for you. From all of this, you can learn and improve your code. The tool that I always use is called <strong>ILSpy.</strong></p><p>Now let me go into the details.</p><h3>.ldstr “Hello World”</h3><p>To start of this, let me write a simple Hello World console application. Then I will go through details and how it works.</p><pre>.assembly extern mscorlib {}<br></pre><pre>.assembly Example<br>{<br>  .ver 1:0:1:0<br>}</pre><pre>.module example.exe</pre><pre>.method static void main() cil managed<br>{</pre><pre>  .maxstack 1</pre><pre>  .entrypoint<br>   </pre><pre>  ldstr &quot;Hello World&quot;  <br>  call void [mscorlib]System.Console::WriteLine (string)</pre><pre>  ret<br>}</pre><p>Ok, we have some code. let us save it as example.il on the location of our choosing. To run our complicated piece of code, we need the <strong>ILAsm.exe</strong>. This is shipped with .NET framework and it can be found in the folder: <strong>&lt;windowsfolder&gt;\Microsoft.NET\Framework\&lt;version&gt;</strong>. For me, I put this in my Path environment variable so I can use it without any problems.</p><p>So, what we need to do, to run our code, is the following:</p><pre><em># I assume that you are in the same folder where </em><br><em># the example.il file is...</em></pre><pre>ilasm example.il</pre><p>When the compilation of the code finishes, you will have in the same folder the newly created executable file with the same name as your .il file (in my case, that will be example.exe). So. we are halfway there, the only thing that is left for us to do is to run our application. The image bellows shows the output and execution of our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*XObM60s6IFPAbmxX." /></figure><p>Voila, our application runs. When you look at it, it already looks like a code that we would write using C#:</p><pre>namespace Example<br>{<br>	class Example<br>	{<br>		static void Main(string[] args)<br>		{<br>			System.Console.WriteLine(&quot;Hello World&quot;);<br>		}<br>	}<br>}</pre><p>Now that we have both implementations, we can see the similarities and the differences. Anyhow, your C# code when compiled will look same (or pretty much similar). If you don’t believe me, you can use ILSpy (or <strong>ILdasm.exe</strong>) to confirm this.</p><p>Now that we know how the IL looks like, let me try to explain what is going on in the example above:</p><ol><li>The first line that we see in the example is an import of the external library. In this particular example, this is mscorlib. In the Visual Studio terminology, this is like adding a reference towards some DLL. Nothing complicated, right?</li><li>The next thing that we see is that we are providing some information about our own assembly. That is, what we are trying to make. So here we are saying, this is the assembly with the name of Example. Inside of here, we are providing even more meta-data like version information of our assembly. There is much more information that we can provide in this “header”.</li><li>Ok, now we are on a line where there is a something new, module. This just defines the module name of our assembly.</li><li>The following lines are now getting more interesting. We are getting into the code. When you look at it, there is a lot similarity with the C# code. It adds more keywords, which are not available in the C#. The difference is that here we have a couple of new things: a) .method begins the definition of the method (you don’t say). b) cil managed is here to indicate to the compiler that the following code should be compiled as a managed code. Hope that you know the difference between the unmanaged and managed code in .NET.</li><li>The next statement actually can have a chapter (or post) for itself, .maxstack. I will try to sum it in a couple of sentences for the sake of this explanation. In short, it is called evaluation stack. What it does is our example, it says that we will allocate at most one place on the stack. So in other words, the evaluation stack is responsible that we have in the memory when we perform an operation on them. In our example, we are moving a string “Hello World” onto the stack before calling a Console.WriteLine on it. After our code is finished processing the values on the evaluation stack they will be removed from it. I hope this makes sense, as said already, this can have a post on its own (which sounds like a good idea).</li><li>Now we are getting to an interesting point. As we are well aware, in the C# environment we are expected to have the Main method. IL is a little bit less strict with this, in a sense that naming is not mandatory. Here we have a .entrypoint to mark a method as an Entry Point of our application. It is easy to check this, go to the previous example and rename the method and test if everything still works as expected. Now try to remove the .entrypoint from the code and see what happens.</li><li>I hope you are not getting tired already. We are now getting to the part where we are going to see how we show in the Console our “Hello World”. This is done by moving our string on the stack, using .ldstr (load string) instruction. I explained this in some detail at step 5, when I was describing evaluation stack. So we first move the string on the stack. Then we can perform an operation (in our case, write it out) on it. More of this in the next step.</li><li>After all of this build up, we are at the place where our string will be written out to the console. Invocation of the methods looks a little bit strange in ILAsm, but still has some resemblance what we see in the C#. First time I saw this, it reminded me to (+ 1 2) in some languages (can someone name say from which language is this particular syntax?). So what is going to happen here is that invocation of System.Console.WriteLine will expect a string as an input. The evaluation stack will be checked for the input and after the processing is finished (string is written out), the string will be removed from the stack.</li><li>And finally, we are ready to return from the method. Hence, at the last place, we see the instruction ret. Phew, a lot of explanations for something that looks so simple. Now I hope that you are at some comfortable level when you see ILAsm you will not get confused. In the following example, I will try to show the simple program with a little bit more complex structure. We will try to add two numbers and print their result. Damn, that sounds really complicated.</li></ol><p>Ok, let us try to multiply two numbers. To make it more interesting, let us also write their result to the Console.</p><pre>.assembly Example<br>{<br>    .ver 1:0:1:0<br>}</pre><pre>.module example.exe</pre><pre>.method static void main() cil managed<br>{<br>    .maxstack 2<br>    .entrypoint<br>    <br>    ldstr &quot;2 * 3 = &quot;<br>    call void [mscorlib]System.Console::Write (string)<br>    <br>    ldc.i4.22<br>    ldc.i4 3   <br>    mul<br>    call void [mscorlib]System.Console::Write (int32)<br>	<br>    ret<br>}</pre><p>This time I will not be focusing to describe every line. I have already gone through most of it in a previous example. Ok, let me start.</p><p>As it can be seen, now we can put on the evaluation stack two items. Well, that makes sense, right? We are trying to multiply two numbers here. It is only logical that we can keep on the stack two items.</p><p>Ok, the next thing that I am doing is writing out “2 * 3 = “. Yup, in this example I will hard-code the values of multiplication. The next example will show how to allow the user to enter the numbers for himself. First I load a string onto the stack and next line is invoking <em>Console.Write.</em> Nothing complicated that we haven’t seen in the previous example.</p><p>Now we are coming to “crucial” part. We are pushing value 2 onto the stack. There are different ways to push an <em>int32</em> onto the stack. Here I am showing two of them. The only difference is, that first format has a limitation (<em>ldc.i4.(number)</em>, where the number goes from 0–8). The second format has no such limitation. It just accepts the number as <em>int32</em> and pushes it onto the stack.</p><p>Now that we have our values prepared on the stack, we are going to use instruction mul. This is the instruction that we were waiting for. Multiply two values from the stack and push the result on the stack. And guess, what? It does what we want. Incredible. The next line only prints the <em>int32</em> to the console. That is the result of the multiplication.</p><p>Woah, that was cool. Now let us up to our game for a little bit. Let us allow the user to enter the values for multiplication. It should not be that hard.</p><pre>.assembly Example<br>{<br>    .ver 1:0:1:0<br>}</pre><pre>.module example.exe</pre><pre>.method static void main() cil managed<br>{<br>    .maxstack 2<br>    .entrypoint<br>    <br>    ldstr &quot;X: &quot;<br>    call void [mscorlib]System.Console::Write (string)<br>	call string [mscorlib]System.Console::ReadLine ()<br>	call int32 [mscorlib]System.Int32::Parse(string)<br>	<br>	ldstr &quot;Y: &quot;<br>    call void [mscorlib]System.Console::Write (string)<br>	call string [mscorlib]System.Console::ReadLine ()<br>	call int32 [mscorlib]System.Int32::Parse(string)<br>	<br>    mul<br>    call void [mscorlib]System.Console::Write (int32)<br>	<br>    ret<br>}</pre><p>As promised, nothing complicated if you know how to write this using C#. The common confusion that I see when I show something like this is that their first guess for the stack size is 4. But as any stack, it is easy to overlook that we are doing push and pop. So when we pop something from the stack, space is free. That is why it is enough, for this example, to only allocate place on the stack for two items.</p><h3>br Exit</h3><p>The world of IL is not somewhere where we would like to dwell on our daily work. For me this is a good practice, just to see how the basis of our work looks like. Especially when I want to look like to what my code compiles. I learned a couple of interesting ways to solve problems in my daily work.</p><p>For the first adventure in the world of IL, I think we did well. In the future adventures I am planning to cover a lot more things:</p><ol><li>Data Types.</li><li>How to declare a variable.</li><li>Loops.</li><li>Conditions / Branching</li><li>and much more.</li></ol><p>Best of luck until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ac79e763fc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time-stamps++ in .NET]]></title>
            <link>https://medium.com/@d34nm/time-stamps-in-net-82495a1c9a1d?source=rss-5d6c9fee8a79------2</link>
            <guid isPermaLink="false">https://medium.com/p/82495a1c9a1d</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[timestamp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dean]]></dc:creator>
            <pubDate>Sun, 13 May 2018 23:38:49 GMT</pubDate>
            <atom:updated>2018-05-14T16:25:36.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOECfw5OL0bUAYTdSMTmeA.png" /></figure><p>Sometimes I even surprise myself when some late-night reading takes me places. Most recently was a discussion that sparked me to write this article. The simple requirement sparked my interest. High-resolution time-stamp. And down the rabbit hole, we go.</p><p>I will not touch upon the discussion that is going around the internet, how good is the implementation of the Date and Time in the .NET. Not interested to start a shouting competition. I still remember the pains that I had when I was working with Java. Fun period. Well, until discovering some 3rd party solutions. But anyhow, the show must go on. I will be focusing on how to get more precise results then you can get using DateTime.Now.</p><h3>What is wrong with DateTime???</h3><p>Depends on the use case, but nothing really. Now let me elaborate in more details what I mean here. The output of the DateTime.Now is based on the system timer. What this means as an output from the system timer:</p><ul><li>Windows 95 and 98 =&gt; 55ms</li><li>Windows NT 3.1 =&gt; 16ms</li><li>Windows NT 3.5 and later =&gt; 10ms</li></ul><p><em>Just a quick refresher, 10,000 ticks = 1 millisecond (10,000,000 ticks = 1 second).</em></p><p>I’m aware that the last two in the list are not relevant, but you can see already the problem. This also implies the domain where the time-stamp precision is important. That is, more precise than 10ms. To be honest, until the project in question it never crossed my path. Then again, that is a fun part of our job. You never know what comes next. At least that is how I look at it.</p><p>Now lets come back to a topic at hand. To check this, you can write a simple console application. In my case, I timed that my clock is precise on the 1ms. This is not that a big. More than adequate for any use-case in the real world. For most timestamps, this will be more than enough. When did user registered in the system? When did I push the notification about the error to the client? Most of this (and similar ones) cases do not need high precision time-stamp.</p><p>Then again, not all problems are the same or I would not be writing this article. What is a nice case is to see in the distributed system when some actions that are related in some manner happened. In other words, a Stopwatch. This is where I got my inspiration for a higher precision time-stamp implementation. I was not interested to pass the instance of the Stopwatch everywhere where I needed, especially when I had a system that was a distributed and decoupled. So no way in hell that I will make a hack.</p><p>So I started to see why everywhere I looked at I found that for higher precision measurements we should use Stopwatch. Every mention of this implementation was saying that is precise on nanosecond level. Hm, that sounds interesting. Let me check.</p><p>No wonder, there was a difference. Now, let us take a look what is that difference and how we can use it in our code.</p><h3>Down the rabbit hole, we go</h3><p>To be precise, Stopwatch implementation has a fallback in a case that high-resolution performance counter is not present. It will use DateTime class then. Now let us talk about the fun part. What is this high-resolution counter and how to get it?</p><p>A little bit of history how we got HPET (high precision event timer). With some mutual research and development, it comes to use from Microsoft and Intel. It is incorporated in the chipsets starting from 2005. So if you are using a Windows XP SP3 or anything after it, you can use this fun new chip. On operating systems before, you are still able to get the ticks, but it can mean that result will come out of “something”. That something can mean PIT (programmable interval timer) or RTC (real-time clock).</p><p>But as how Microsoft is publishing operating systems in recent years, we are getting updates once per year at least :). So we should be safe and sound. Now, let me drop some code and explain how you can use this in your code. The functionality that we need, lives in the kernel32.dll. Don’t get angry, I think it was obvious that we will need P/Invoke to get something like this inside of the .NET.</p><pre>public class TimestampPlusPlus<br>{<br>   public static bool QueryPerformanceFrequency(out long value)<br>   {<br>	return Interop.QueryPerformanceFrequency(out value);<br>   }</pre><pre>   public static bool QueryPerformanceCounter(out long value)<br>   {<br>	return Interop.QueryPerformanceCounter(out value);<br>   }</pre><pre><em>   // Windows 8 and onwards<br>   </em>public static long GetSystemTimePreciseAsFileTime()<br>   {<br>	long retVal = 0;<br>	Interop.QuerySystemTimeAsFileTime(out retVal);<br>	return retVal;<br>   }<br>}</pre><pre><em>// I usually make this even more cleaner, but for sake of example</em><br><em>// it is more than good...</em><br>internal class Interop<br>{<br>   [DllImport(&quot;kernel32.dll&quot;)]<br>   static extern bool QueryPerformanceFrequency(out long value);</pre><pre>   [DllImport(&quot;kernel32.dll&quot;)]<br>   static extern bool QueryPerformanceCounter(out long value);</pre><pre>   [DllImport(&quot;kernel32.dll&quot;)]<br>   static extern void QuerySystemTimeAsFileTime(out long value);<br>}</pre><p>This is a very simple implementation, just for demonstrative purposes. I will probably make my GitHub implementation open soon. Now let me talk about the value and what you can expect as an output of this two functions. Plus, why you need to have two of them.</p><p>First, let us see what is the <em>QueryPerformanceFrequency</em> all about and why we need it. The output of this function is the frequency (duh, you don’t say) of the high-performance counter ticks per second. Mouthful. What is important to know that there is a difference between .NET ticks and ticks measured using this method. Also, it doesn’t change while the system is running, so it opens some optimizations (like, static field initialized in the static constructor). And, if the value is <strong>0</strong> we can say that our system doesn’t have HPC available. So if you need to convert them to .NET ticks for some reason, some simple conversion needs to be applied. I will describe this when I explain QueryPerformanceCounter, so next paragraph.</p><p>Now that we are aware of the <em>QueryPerformanceFrequency</em> we can continue in explaining the <em>QueryPerformanceCounter</em>. The output is as expected. Ticks. Now, what I mentioned in the previous paragraph, there is a difference between the .NET ticks and the ticks that we get as output. Small conversion should be applied if you want to use them as .NET ticks. If this is not the case then you only need <em>QueryPerformanceCounter</em>(<em>QueryPerformanceFrequency</em> is required for this conversion).</p><pre><em>// example:</em><br>long frequency = 0;<br>long ticks = 0;<br>long dotNetTicks = 0;</pre><pre><em>// no check if the call is successful, I know</em><br>TimestampPlusPlus.QueryPerformanceFrequency(out frequency); </pre><pre><em>// here as well, what now???</em><br>TimestampPlusPlus.QueryPerformanceCounter(out ticks);		</pre><pre><em>// 1e7 = 10,000,000 =&gt; guess what it stands for (check refresher)</em><br>dotNetTicks = (long)(ticks / (frequency / 1e7));</pre><p>Now let me show the conversion that I was mentioning little bit earlier:</p><pre>private long Ticks <br>{ <br>  get <br>  {<br>    <em>// implementation from a previous code snippet...</em><br>  }<br>}</pre><pre>private long Offset<br>{<br>  get <br>  {<br>    return Ticks - DateTime.Now.Ticks; <em>// some caching would be nice</em><br>  }<br>} </pre><pre><em>// not that complicated, right?   </em><br>public DateTime Now<br>{<br>   return new DateTime(Ticks - Offset);<br>}</pre><p>This closes the story that demonstrates the things before Microsoft released Windows 8. There, as seen in the snippets there is a new function that makes this really simple. P/Invoke is still needed, but the output is something that we can use without any additional conversion.</p><p>The <em>GetSystemTimePreciseAsFileTime</em> is a new kid on the block. The <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/hh706895(v=vs.85).aspx">MSDN</a> is very descriptive and the only difference to our previous solution is that output of this function is in UTC. For me the solution at the end was simple. During initialisation, I would decide what implementation to use based on the underlying OS. Be that QPC for the OS before Windows 8 or QPC for the supported operating systems. Simple design pattern.</p><h3>Finishing touches</h3><p>Something that started as a simple interested opened a lot of interesting articles and implementations that I found over the internet. I was a little bit surprised about some of the things that I considered to be done differently. Then again, as most of the use-cases will be satisfied with the usual way, no reason to make our life even more complicated? That is why the managers are there, right? :)</p><p>I’m hoping to soon push my final touches to GitHub and make it public for everyone else to see. I will leave the link here when I’m done. Hope that you found this article useful and until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82495a1c9a1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>