473,804 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Surprising results

Imagine if someone asked which of the follwing two methods of encoding
an integer into a byte array was quicker.

The purpose is in preparation for sending across a socket as part of a
'header'.
If you are curious, run the code yourself.

if(args.Length != 1)
{
Console.WriteLi ne("Usage: {0} <iterations>" ,
System.AppDomai n.CurrentDomain .FriendlyName);

return;
}

int[] size = new int[Convert.ToInt32 (args[0])];
for(int i = 0; i < size.Length; i++)
size[i] = i;

HiPerfTimer timer = new HiPerfTimer();

byte[] headerBuf = null;
timer.Start();
for(int i = 0; i < size.Length; i++)
{
// convert the int to a byte array in network byte
order
headerBuf = BitConverter.Ge tBytes(size[i]);
}
timer.Stop();
long bitConvert = timer.usec;

byte[] bas = null;
timer.Start();
for(int i = 0; i < size.Length; i++)
{
bas = new byte[4];
bas[0] = (byte)(size[i] >> 24);
bas[1] = (byte)(size[i] >> 16);
bas[2] = (byte)(size[i] >> 8);
bas[3] = (byte)(size[i]);
}
timer.Stop();
long bitShift = timer.usec;

Console.WriteLi ne("BitShift method on sample of length {0}
took {1} microseconds", size.Length, bitShift );
Console.WriteLi ne("BitConverte r method on sample of length
{0} took {1} microseconds", size.Length, bitConvert );
Nov 16 '05 #1
12 1745
After 100 mil iterations, I get 23 seconds for the BitConverter and only 17 for
the bit shifting.

Also, for more precise results (which made little difference), I changed thebit
conversion portion into a function which is similar to the GetBytes declaration
so that it couldn't be said the the difference in time is the overhead for
function calls. If there was a difference, it is VERY VERY small.

Mythran

"Jack" <ja**@yankeeboy software.com> wrote in message
news:bb******** *************** ***@posting.goo gle.com...
Imagine if someone asked which of the follwing two methods of encoding
an integer into a byte array was quicker.

The purpose is in preparation for sending across a socket as part of a
'header'.
If you are curious, run the code yourself.

if(args.Length != 1)
{
Console.WriteLi ne("Usage: {0} <iterations>" ,
System.AppDomai n.CurrentDomain .FriendlyName);

return;
}

int[] size = new int[Convert.ToInt32 (args[0])];
for(int i = 0; i < size.Length; i++)
size[i] = i;

HiPerfTimer timer = new HiPerfTimer();

byte[] headerBuf = null;
timer.Start();
for(int i = 0; i < size.Length; i++)
{
// convert the int to a byte array in network byte
order
headerBuf = BitConverter.Ge tBytes(size[i]);
}
timer.Stop();
long bitConvert = timer.usec;

byte[] bas = null;
timer.Start();
for(int i = 0; i < size.Length; i++)
{
bas = new byte[4];
bas[0] = (byte)(size[i] >> 24);
bas[1] = (byte)(size[i] >> 16);
bas[2] = (byte)(size[i] >> 8);
bas[3] = (byte)(size[i]);
}
timer.Stop();
long bitShift = timer.usec;

Console.WriteLi ne("BitShift method on sample of length {0}
took {1} microseconds", size.Length, bitShift );
Console.WriteLi ne("BitConverte r method on sample of length
{0} took {1} microseconds", size.Length, bitConvert );

Nov 16 '05 #2
> After 100 mil iterations, I get 23 seconds for the BitConverter and only 17 for
the bit shifting.

This is what my results indicated as well. I am surprised that there
could be such a difference, which makes me wonder what the
BitConverter function is doing.
Nov 16 '05 #3

"Jack" <ja**@yankeeboy software.com> wrote in message
news:bb******** *************** ***@posting.goo gle.com...
Imagine if someone asked which of the follwing two methods of encoding
an integer into a byte array was quicker.

The purpose is in preparation for sending across a socket as part of a
'header'.


Two things:

1) When you post code like this, post the whole damn file. Having to write
it out is a pain, especially when you have to guess what namespaces where in
use, which leads me to
2) When you use an assembly or class that isn't part of the framework,
*ALWAYS* mention it and provide a link(or include it if appropriate). It
irks people less. The HiPerfTimer I found *doesn't* work with your code, so
for the moment I am giving up on this and moving on.
Nov 16 '05 #4
Touchy Touchy...I was able to write the HiPerfTimer in < 10 minutes, the missing
piece of his code was easily created automatically by the IDE when you do
File->New->Console Application :P

Is it really that aggravating? Just wondering, no offense intended...

Mythran
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in message
news:uz******** ******@TK2MSFTN GP12.phx.gbl...

"Jack" <ja**@yankeeboy software.com> wrote in message
news:bb******** *************** ***@posting.goo gle.com...
Imagine if someone asked which of the follwing two methods of encoding
an integer into a byte array was quicker.

The purpose is in preparation for sending across a socket as part of a
'header'.


Two things:

1) When you post code like this, post the whole damn file. Having to write
it out is a pain, especially when you have to guess what namespaces where in
use, which leads me to
2) When you use an assembly or class that isn't part of the framework,
*ALWAYS* mention it and provide a link(or include it if appropriate). It
irks people less. The HiPerfTimer I found *doesn't* work with your code, so
for the moment I am giving up on this and moving on.

Nov 16 '05 #5
Mythran <ki********@hot mail.com> wrote:
Touchy Touchy...I was able to write the HiPerfTimer in < 10 minutes,
the missing piece of his code was easily created automatically by the
IDE when you do File->New->Console Application :P

Is it really that aggravating? Just wondering, no offense intended...


It is when you're trying to spend time helping people with things they
don't know how to do rather than doing things they've already done.

Wasting five minutes per question is a good way to push the number of
questions that get answered right down.

See http://www.pobox.com/~skeet/csharp/complete.html for my suggestions
on this matter. If I'm making a post and I want other people to run
some code I've written, it's up to me to make it as easy as possible
for others to run that code.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6

"Mythran" <ki********@hot mail.com> wrote in message
news:eg******** ******@tk2msftn gp13.phx.gbl...
Touchy Touchy...I was able to write the HiPerfTimer in < 10 minutes, the
missing
piece of his code was easily created automatically by the IDE when you do
File->New->Console Application :P

Is it really that aggravating? Just wondering, no offense intended...


It can be. Here is a rough breakdown of what I did last night:
1) Ok, no using statements, but everything looks like just System, except
for HiPerfTimer.
2) type out using System;, public class Test { public static void
Main(string[] args) { <paste> } }
3) HiPerfTimer doesn't look familiar, lets look it up to figure out what
namespace its in
4) Hrmm, not in the 1.1 or 2.0 frameworks, so it must be third party
5) google
6) Code Project -> HiPerfTimer
7) download code, open file, copy, paste into other file
8) compile, error out.
9) Come complain becuase I've had to take too many steps to try to get this
to work.
Also, for benchmarks like this I don't use the IDE, ;). I use a quick little
editor called Crimson Editor for benchmarks and quick tests, instead of
loading VS for every file I try to compile(also, the editor helps since I
only have one version of visual studio installed at home, I can compile with
seperate compilers to see if runtime version changes the results).

Also, I would worry about using a benchmark where my timer and your timer
were written by different people, its possible the error was in your timer
code, either due to a bug in the runtime or due to a mistake you made. Or I
could make a mistake and skew my results.

Either way, its always best to provide everything. Like Jon said, 5 minutes
for every message doesn't let you get through too many.
Nov 16 '05 #7
Anywho, hope y'all didn't get offended by my previous reply to ya...just
wonderin'..

:) Now I know...and know is half...<zZzZzZ>

Mythran

"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in message
news:uj******** *****@TK2MSFTNG P11.phx.gbl...

"Mythran" <ki********@hot mail.com> wrote in message
news:eg******** ******@tk2msftn gp13.phx.gbl...
Touchy Touchy...I was able to write the HiPerfTimer in < 10 minutes, the
missing
piece of his code was easily created automatically by the IDE when you do
File->New->Console Application :P

Is it really that aggravating? Just wondering, no offense intended...

Nov 16 '05 #8

"Mythran" <ki********@hot mail.com> wrote in message
news:uB******** ******@TK2MSFTN GP15.phx.gbl...
Anywho, hope y'all didn't get offended by my previous reply to ya...just
wonderin'..


Not at all, I was just annoyed, ;).
Nov 16 '05 #9
>
Two things:

1) When you post code like this, post the whole damn file. Having to write
it out is a pain, especially when you have to guess what namespaces where in
use, which leads me to
2) When you use an assembly or class that isn't part of the framework,
*ALWAYS* mention it and provide a link(or include it if appropriate). It
irks people less. The HiPerfTimer I found *doesn't* work with your code, so
for the moment I am giving up on this and moving on.


In response to your 'Two Things'

1.) "...post the whole damn file" - really ?!?!? It just happens that
the 'whole damn file' is littered with snippets of code that would
probably confuse you, and would never link since they reference many
non .NET assemblies. OK I admit I could have yanked the code off into
its own project and given the entire listing like that, but, surely
you could just as easily have done that if you were remotely
interested in the issue. The code as presented illustrates the issue
without the burden of non-relevant code. Get off your high horse.

2) "When you use an assembly or class ..." Wow, HiPerfTimer gives you
an unresolved symbol ? Comment it out ! I agree you might be
slightly inconvenienced, but if you are interested in the issue, it's
pretty insignificant. Its use is obvious, you probably already have
your own High Performance Timer class you could easily slot in - if
not here it is
using System.Runtime. InteropServices ;
class HiPerfTimer
{
[DllImport("Kern el32.dll")]
private static extern bool QueryPerformanc eCounter(out long
lpPerformanceCo unt);

[DllImport("Kern el32.dll")]
private static extern bool QueryPerformanc eFrequency(out long
lpFrequency);

private long start, stop, freq;

// Constructor
public HiPerfTimer()
{
start= 0;
stop= 0;

if (QueryPerforman ceFrequency(out freq) == false)
{
// high-performance counter not supported
throw new System.Exceptio n("Performanc e Counter not
supported - bizarre !");
}
}

// Start the timer
public void Start()
{
QueryPerformanc eCounter(out start);
}

// Stop the timer
public void Stop()
{
QueryPerformanc eCounter(out stop);
}

// Returns the duration of the timer (in microseconds)
public long usec
{
get
{
return (long)(((double )(stop - start) / (double) freq
)*(double)10000 00);
}
}
// Returns the duration of the timer (in milliseconds)
public long msec
{
get
{
return (long)(((double )(stop - start) / (double) freq
)*(double)1000) ;
}
}
// Returns the duration of the timer (in seconds)
public double sec
{
get
{
return (long)((double) (stop - start) / (double) freq );
}
}

}

Again, the relevant code is present, in fact I have provided more code
than I really should have, I could easily have simply asked this
question

why is

BitConverter.Ge tBytes()

so slow compared to

byte[] myConvert(int val)
{
byte[] ret = new byte[4];
ret[0] = (byte)(val >> 24);
ret[1] = (byte)(val >> 16);
ret[2] = (byte)(val >> 8);
ret[3] = (byte)(val);
return ret;
}

But I decided to give you a framework for illustrating how slow it is.

As a side note: I realise you probably spent a long time becoming an
MVP, however, don't let it go to your head. There are plenty of us
out there who are also MVPs who are more humble than you, and don't
choose to advertise the fact by adding it to our signatures.
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1852
by: Michael Cornelius | last post by:
As an old C programmer, I'm surprised by some results I'm getting with integer division. For example: >>> -1/1000 -1 >>> -9/2 -5 I expect the results of these expressions to be 0 and -4, respectively.
2
3539
by: CharitiesOnline | last post by:
Hello, I have set this script up to add paging to a search results page. Which on the first page works fine. I calculates how many pages there should be depending on the number of results returned from my search and how many records I have set it to display per page. All great so far, HOWEVER..... When you click the next link to see the next 10 results on the next page, it just dumps the search details and pulls up all the records in the...
2
1188
by: pavan | last post by:
See the following code : #include <iostream> using namespace std; float f1 = 1.0e+6; // This function just returns f1. float value1()
1
3548
by: Don | last post by:
I am new to Indexing Services, have been researching the MS Site as well as web articles on DevHood, etc. I have set up a seperate catalog ("KnowledgeBase") on Win XP with a number of files. I am trying to use OLEDB through ADO to search results and serve them up onto an ASP.Net web page, yet I consistently get back 0 results. I have this working fine in a console application. I think my problem is I have to allow IIS access to my IS...
0
1907
by: Rob | last post by:
I doubt this is the best way to do it, but what I came up with was to hide the XML in an HTML Comment then edit the file deleting the HTML stuff and keep the XML results. If anyone has a better solution, I would be interested. Thank you. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim cmd As System.Data.SqlClient.SqlCommand cmd = New System.Data.SqlClient.SqlCommand
4
1642
by: jaYPee | last post by:
I have downloaded some source code but I want this to convert the results into datagrid. dr = cmd.ExecuteReader() '**************************************** ' SHOW THE RESULTS '**************************************** sResults = "CustomerID" + vbTab + "ContactName" + vbTab +
7
1431
by: codergem | last post by:
Hello Friends Can anyone help me where exactly at what address the *p is storing the updated value ( which is 99). const int k=9; int *p=(int *)&k; cout<<"Addr of k : "<<&k<<" "<<p;
45
2947
by: charles.lobo | last post by:
Hi, I have recently begun using templates in C++ and have found it to be quite useful. However, hearing stories of code bloat and assorted problems I decided to write a couple of small programs to check. What I expected was that there would be minor code bloat and some speed improvement when using templates. However... I wrote a basic list container (using templates), and a list container (using virtual derived classes). I also tried...
4
5699
by: David Abrahams | last post by:
I'm seeing highly surprising (and different!) behaviors of PyImport_ImportModule on Linux and Windows when used in a program with python embedding. On Linux, when attempting to import a module xxx that's in the current directory, I get ImportError: No module named xxx I can work around the problem by setting
0
9712
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10341
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10089
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9171
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.