This program is given in the following website. It is compiling but not producing any output. Please correct it.
http://www.dotnetperls.com/static-field
using System;
using System.Diagnostics;
class Test1
{
int _a; // Instance fields:
int _b;
int _c;
public void X()
{
this._a++; // Change instance field values:
this._b++;
this._c++;
}
}
class Test2
{
static int _a; // Static fields:
static int _b;
static int _c;
public void X()
{
_a++; // Change static field values:
_b++;
_c++;
}
}
class Program
{
const int _max = 200000000;
static void Main()
{
Test1 test1 = new Test1(); // Instantiate instance fields
Test2 test2 = new Test2(); // Instantiate
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
test1.X(); // Instance fields:
test1.X();
test1.X();
test1.X();
test1.X();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
test2.X(); // Static fields:
test2.X();
test2.X();
test2.X();
test2.X();
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00") + " ns");
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00") + " ns");
Console.ReadKey();
}
}
Loading
Posted Jul 4, 2013, 4:31 PM
Sanjeeb LenkaPosted Jul 4, 2013, 3:48 PM
the code is correct there is problem in the loop i modified your code check it.
this output is not coming because of the loop is running for 200000000 times. so you have wait for some time to get the output. if you want reduce the loop iteration you can modify by reducing the loop count.
from
const int _max = 200000000;
to
const int _max = 2000;
using System;
using System.Diagnostics;
class Test1
{
int _a; // Instance fields:
int _b;
int _c;
public void X()
{
this._a++; // Change instance field values:
this._b++;
this._c++;
}
}
class Test2
{
static int _a; // Static fields:
static int _b;
static int _c;
public void X()
{
_a++; // Change static field values:
_b++;
_c++;
}
}
class Program
{
const int _max = 2000;
static void Main()
{
Test1 test1 = new Test1(); // Instantiate instance fields
Test2 test2 = new Test2(); // Instantiate
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
test1.X(); // Instance fields:
test1.X();
test1.X();
test1.X();
test1.X();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
test2.X(); // Static fields:
test2.X();
test2.X();
test2.X();
test2.X();
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00") + " ns");
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00") + " ns");
Console.ReadKey();
}
}
VulpesPosted Jul 4, 2013, 3:36 PM
The first time I ran it the output was:
and the second time gave: