Custom Performance Counter / Minute in .NET - performancecounter

I'm trying to create a custom performance counter in C# based on per minute.
So far, I've seen only RateOfCountsPerSecond32 or RateOfCountsPerSecond64 available.
Does anybody know what are options for creating a custom counter based on per minute?

This won't be directly supported. You'll have to computer the rate per minute yourself, and then use a NumberOfItems32 or NumberOfItems64 counter to display the rate. Using a helpful name like "Count / minute" will make it clear what the value is. You'll just update the counter every minute. A background (worker) thread would be a good place to do that.
Alternately, you can just depend upon the monitoring software. Use a NumberOfItems32/64 counter, but have the monitoring software do the per-minute computation. The PerfMon tool built into Windows doesn't do this, but there's no reason it couldn't.

By default PerfMon pulls data every second. In order to get permanent image in Windows performance monitor chart, I've wrote custom counter for measure rate of count per minute.
After working for one minute I become receive data from my counter.
Note that accuracy doesn't important for me.
Code snippet look like this:
class PerMinExample
{
private static PerformanceCounter _pcPerSec;
private static PerformanceCounter _pcPerMin;
private static Timer _timer = new Timer(CallBack, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
private static Queue<CounterSample> _queue = new Queue<CounterSample>();
static PerMinExample()
{
// RateOfCountsPerSecond32
_pcPerSec = new PerformanceCounter("Category", "ORDERS PER SECOND", false);
// NumberOfItems32
_pcPerMin = new PerformanceCounter("Category", "ORDERS PER MINUTE", false);
_pcPerSec.RawValue = 0;
_pcPerMin.RawValue = 0;
}
public void CountSomething()
{
_pcPerSec.Increment();
}
private static void CallBack(Object o)
{
CounterSample sample = _pcPerSec.NextSample();
_queue.Enqueue(sample);
if (_queue.Count <= 60)
return;
CounterSample prev = _queue.Dequeue();
Single numerator = (Single)sample.RawValue - (Single)prev.RawValue;
Single denomenator =
(Single)(sample.TimeStamp - prev.TimeStamp)
/ (Single)(sample.SystemFrequency) / 60;
Single counterValue = numerator / denomenator;
_pcPerMin.RawValue = (Int32)Math.Ceiling(counterValue);
Console.WriteLine("ORDERS PER SEC: {0}", _pcPerSec.NextValue());
Console.WriteLine("ORDERS PER MINUTE: {0}", _pcPerMin.NextValue());
}
}

Related

Repast Simphony: Scheduling a global behavior as Poisson process with random intervals

I have a functioning model where I want to force a random agent to change state on a varying interval, modeled as a Poisson arrival process. I have set up a global behavior per the FAQ, by including a block in Build() that looks like this (where a and b are externalized in parameters.xml):
ISchedule schedule = RunEnvironment.getInstance().getCurrentSchedule();
ScheduleParameters arrival = ScheduleParameters.createPoissonProbabilityRepeating(a, b, 1);
schedule.schedule(arrival , this, "arrivalEvent");
Then I have a context method that looks like this:
public void arrivalEvent() {
// stuff
double tick = RunEnvironment.getInstance().getCurrentSchedule().getTickCount();
System.out.println("New arrival on tick: " + tick);
}
This appears to work, except that it appears from the debug text to use the same value for b on all repeats. Is there a way for each repeat to use a new random draw? Or is there another (better) way to achieve this?
If you want b to vary each time, one way to do this is to reschedule arrivalEvent in arrivalEvent itself. The most legible way to do this is by implementing arrivalEvent as a class that implements IAction.
public class ArrivalEvent implements IAction {
private Poisson poisson;
public ArrivalEvent(Poisson poisson) {
this.poisson = poisson;
}
public void execute() {
// execute whatever the actual arrival event is
// reschedule
double next = poisson.nextDouble() + RunEnvironment.getInstance().getCurrentSchedule().getTickCount();
RunEnvironment.getInstance().getCurrentSchedule().schedule(ScheduleParameters.createOneTime(next, 1), this);
}
}
And schedule it for the first time with something like
Poisson poisson = RandomHelper.getPoisson();
double next = poisson.nextDouble();
RunEnvironment.getInstance().getCurrentSchedule().schedule(ScheduleParameters.createOneTime(next, 1), new ArrivalEvent(poisson));
Nick

Ticks are inconsistent and are fluctuating

I have a sub and a button. And the code is like this:
Private Sub plus(ByRef a As Integer)
For i = 0 To a
a = a + a
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer = 19
Dim sw As New Stopwatch
sw.Start()
plus(i)
sw.Stop()
MsgBox(sw.ElapsedTicks)
End Sub
when I run the sub is by clicking the "button1" the program to output 310 thats means 310 is sw.elapsedticks
When I run the sub again by clicking the "button1" again, the program to output 1 << JUST ONE ellapsedticks
How can it be like that ?
I tried to stop my vb.net program and I run it again, and then I click its button again, it happened the same, which is worth 272 stopwatch elapsedticks then after I click again stopwatch , elapsedticks instead be 1 again
Please explain why it could happen?
The StopWatch class will fallback to using DateTime class and uses ticks for the measurements if your hardware doesn't support high-performance counter. Most computer's now day's, at least from Windows 2000 and later, have high-performance counters. With this in mind, the .NET Stopwatch class is based on this high frequency timer. In general, calling Start queries the performance counter and stores the value. When you Stop, it queries the performance counter again. Then the elapsed time is a simple subtraction of those two values to give you your ElapsedTicks.
Here are a few items to have a look at for further explanation...
This property just makes a call to GetRawElapsedTicks()
public long ElapsedTicks {
get { return GetRawElapsedTicks(); }
}
The below function returns the actual time that has elapsed from the time the stopwatch was started to when the stopwatch Stop method was called. As mentioned above, the elapsed time is a simple subtraction of those two values you can see that below: currentTimeStamp - startTimeStamp.
// Get the elapsed ticks.
#if FEATURE_NETCORE
public long GetRawElapsedTicks() {
#else
private long GetRawElapsedTicks() {
#endif
long timeElapsed = elapsed;
if( isRunning) {
// If the StopWatch is running, add elapsed time since
// the Stopwatch is started last time.
long currentTimeStamp = GetTimestamp();
long elapsedUntilNow = currentTimeStamp - startTimeStamp;
timeElapsed += elapsedUntilNow;
}
return timeElapsed;
}
Above you may notice the #if FEATURE_NETCORE and wonder what it is. These are called preprocessor commands. Basically they work like if-else statements except that if the condition isn't met it will not include the code at compile time as it's a pre-compile decision and not runtime...
With this all said, it was mentioned above already by Hans Passant about just in time (JIT) compiling. All of this I mentioned above breaks this down further for explanation. The real reason for the difference is the time it is taking for it to compile and run the first time.
Another thing to mention. The stopwatch class uses a long variable type to store what they call frequency. Frequency" stores the frequency of the high-resolution performance counter if one exists, otherwise it will store TicksPerSecond. The frequency cannot change while the system is running, so it's only initialized once.
Below are other constants that have a great deal with frequency and how it's calculated as well.
private const long TicksPerMillisecond = 10000;
private const long TicksPerSecond = TicksPerMillisecond * 1000;
When you create a new instance of the StopWatch class this is what is ran.
bool succeeded = SafeNativeMethods.QueryPerformanceFrequency(out Frequency);
if(!succeeded) {
IsHighResolution = false;
Frequency = TicksPerSecond;
tickFrequency = 1;
}
else {
IsHighResolution = true;
tickFrequency = TicksPerSecond;
tickFrequency /= Frequency;
}
Frequency as you can now see , has a big role in setting up how the elapsed time is going to be calculated and how often the tick is going to occur. Even when you stop your application it doesn't matter as the frequency is stored at this time. The only way to reset the frequency is to reboot your machine.

How do I gradually apply velocity in Spigot?

I am using player.setVelocity(player.getLocation().getDirection().multiply(Main.instance.getConfig().getDouble("velocity_multiplier")).setY(Main.instance.getConfig().getInt("Y_axis"))); to set velocity to a player. It allows high configuration of movement via config, but the problem is that when you set it too high, Spigot blocks it. I do not want to enable:
server.properties: allow_flight.
So how can I avoid this? I bumped up the multiplier to 30 just for a test, and it would start to move you, glitch, and pull you back down. It also says that the player moved too quickly in console even from smaller amounts of velocity. I was thinking of making it gradually apply the velocity. When you jump, it applies the starting velocity and as you go it goes higher(Y_axis) and farther(velocity_multiplier), but I do not know how to do that.
You can enable just for the player before applying the velocity and in a delayed task disabled it
public void blabla(Player player){
player.setAllowFlight(true);
player.setVelocity(player.getLocation().getDirection().multiply(Main.instance.getConfig().getDouble("velocity_multiplier")).setY(Main.instance.getConfig().getInt("Y_axis")));
new BukkitRunnable() {
#Override
public void run() {
player.setAllowFlight(false);
}
}.runTaskLater(this, 20 * 5);
}
In the code I used 20 * 5 to disable the flight after 5 seconds, you can change it to what you want.
Beyond code, you likely would be best situated to address your issue by allowing flight in the Spigot file and installing or developing an anti-cheat in the game. Spigot's flight protection works poorly with many plugins and does not successfully block many players who attempt to fly.
Best advice would be to look beyond a makeshift code solution and rather create your own anti-fly.
The maximum velocity in bukkit (and spigot) is 10 blocks per tick. This is all directions combined.
If your initial velocity is to high, you can use the scheduler to repeatedly calculate the next velocity.
To calculate this, we need some magic values: The following values come from The Minecraft Wiki.
private final static double DECELERATION_RATE = 0.98D;
private final static double GRAVITY_CONSTANT = 0.08D;
private final static double VANILA_ANTICHEAT_THRESHOLD = 9.5D; // actual 10D
We first need to calculate the spot the player would reach using those speeds, and then teleport him while applying the velocity for the first part.
We are going to use a BukkitRunnable to run a task that calculates the above:
Vector speed = ...;
Player player = ...;
new BukkitRunnable() {
double velY = speed.getY();
Location locCached = new Location(null,0,0,0);
#Override
public void run() {
if (velY > VANILA_ANTICHEAT_THRESHOLD) {
player.getLocation(locCached).setY(locCached.getY() + velY);
player.teleport(locCached);
player.setVelocity(new Vector(0,ANILA_ANTICHEAT_THRESHOLD,0));
} else {
player.setVelocity(new Vector(0,velY,0));
this.cancel();
}
velY -= GRAVITY_CONSTANT;
velY *= DECELERATION_RATE;
}
}.runTaskTimer(plugin,0,1);
The above code will then handle the velocity problems for us and can be used in place of setVelocity.

How to rotate windows forms in every 20 secs using timer in windows application?

I have four windows forms namely, form1.vb, form2.vb, form3.vb, form4.vb.
And also i have one master page namely form5.vb. So i have rotate one by one above four windows forms in form5.vb with every 20 secs . how to do it ?
On a 20 second timer you can call 'BringToFront' on each form.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.bringtofront.aspx
Basically, you create a timer and call the function BringToFront on each form.
In C#:
static int counter = 1;
static void StartRotating()
{
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Interval = 20000; // 20 seconds
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Start();
}
private static void TimerEventProcessor(Object myObject,
EventArgs myEventArgs) {
// you could use a switch statement also
if(counter==1) form1.BringToFront();
if(counter==2) form2.BringToFront();
if(counter==3) form3.BringToFront();
if(counter==4) {
form4.BringToFront();
counter=0; //reset counter
}
counter++;
}
You need to keep an index to know which form is currently displayed and then in the timer elapsed event you can do this
formtoshow.TopMost = true;
formtoshow.BringToFront();

.NET multi-threaded variable access

I have an application with 4 threads. (GUI, Controller, Producer, Consumer)
The GUI is self-explanatory.
The controller starts the producer and consumer threads after some intial setup.
The producer creates items and places them in a free slot in a "ring buffer"
The consumer takes items from the "ring buffer" and writes them to disk.
The producer creates items at a much higher rate than the consumer.
The consumer is IO heavy and IO bound.
Currently I am checking a variable in each ring buffer slot to determine if it can be written to.
if Slot.Free then
Write Slot.Data To Disk
end if
I am not using lock/synclock instead I'm just reading / writing the value of the slot's "free" variable. I don't believe that is correct even though it is a volatile read/write. Is there a better method to read/write this variable? The variable is of type "integer" and is either 0 or 1.
You mention using a ring buffer, but a (properly implemented) ring buffer would be able to determine if it's full without checking all it's elements, eliminating the need for a boolean in each slot.
I'm not used to VB.NET, but this should be a working (if crude) implementation of a ring buffer that blocks when it's full / empty on respective write / read actions.
Friend Class RingBuffer(Of T)
Private _slots() As T
Private _head As Integer
Private _tail As Integer
Private _readableSlots As Semaphore
Private _readLock As Object
Private _writableSlots As Semaphore
Private _writeLock As Object
Public Sub New(ByVal size As Integer)
ReDim _slots(size - 1)
_head = 0
_tail = 0
_readLock = New Object
_writeLock = New Object
_readableSlots = New Semaphore(0, size)
_writableSlots = New Semaphore(size, size)
End Sub
Public Function Dequeue() As T
Dim item As T
_readableSlots.WaitOne()
SyncLock _readLock
item = _slots(_head)
_head = (_head + 1) Mod _slots.Length
End SyncLock
_writableSlots.Release()
Return item
End Function
Public Sub Enqueue(ByVal item As T)
_writableSlots.WaitOne()
SyncLock _writeLock
_slots(_tail) = item
_tail = (_tail + 1) Mod _slots.Length
End SyncLock
_readableSlots.Release()
End Sub
End Class
Once you have that, your Producer and Consumer can be really dumb :) It's not exactly guaranteed that items are processed in-order if you have multiple consumers however:
Private _buffer As RingBuffer(Of Integer) = New RingBuffer(Of Integer)(5)
Private Sub Producer()
Dim i As Integer = 0
Do While True
_buffer.Enqueue(i)
i = i + 1
Loop
End Sub
Private Sub Consumer()
Do While True
Debug.WriteLine(("Consumer A: " & _buffer.Dequeue))
Thread.Sleep(1000)
Loop
End Sub
There are several ways you can do this safely.
If your architecture and requirements allow it, you can use custom events so one thread can simply signal a different listening thread to notify that a variables state has been changed. You do have to keep track of who is consuming what events though, and if those consumers are read-only on the variable, or read/write.
You can also use a simple custom wrapper class around a variable type (or use a generic) that does the lock/unlock code for you. In VB.NET, I've found that using the Monitor class to lock the private instance variable is really handy.
Mutexes and semaphores - .NET has a Mutex class and a Semaphore class. These both assist in controlling access to thread-shared variables. I like Mutexes because they're so easy to use, and you don't need to keep track of how many threads might have access to a given resource.
Please DO note that although some MSDN documentation claims that reading to or writing from a value-type (Integer, Double, etc) is an atomic operation, and hence "thread-safe", this is SELDOM TRUE in actual VB code. A simple statement like X = Y is NOT in fact atomic, as it you have to perform two operations here - first, loading the value of Y, and then setting the value of X. Little things like this make me lose my hair :)
Whatever method you decide to roll with, I find that liberal commenting throughout your code describing who has access to what resources at what time is invaluable - three months from now, you're not gonna remember the fine points of this code and comments really help.
Best of luck!
You could use Semaphores to solve the Producer Consumer problem:
static void Main(string[] args)
{ new Thread(Producer).Start(); new Thread(Consumer).Start(); }
static int K = 10;
static n = new Semaphore(0, K), e = new Semaphore(K, K);
static int[] buffer = new int[K];
static int _in, _out;
static void Producer()
{
while (true)
{
e.WaitOne();
buffer[_in] = produce();
_in = (_in + 1) % buffer.Length;
n.Release();
}
}
static void Consumer()
{
while (true)
{
n.WaitOne();
var v = buffer[_out];
_out = (_out + 1) % buffer.Length;
e.Release();
consume(v);
}
}
Any time that data can be accessed by more than one thread, you have to write your code to assume that it will be accessed by more than one thread. "Murphy's Law" rules multithreaded scenarios.
For instance, if one thread is filling a slot, and the other is emptying it, you need a lock around it.
You can make your checks interlocked operations and eliminate any concern:
const FREE = 0;
const FILLING = 1;
const READY = 2;
const DRAINIG = 3;
Producer:
if (FREE == Interlocked.CompareExchange(ref slotFlag, FILLING, FREE))
{
fillslot();
old = Interlocked.Exchange(ref slotFlag, READY);
Debug.Assert (FILLING == old);
}
Consumer:
if (READY == Interlocked.CompareExchange(ref slotFlag, DRAINIG, READY))
{
drain_slot();
old = Interlocked.Exchange(ref slotFlag, FREE);
Debug.Assert( DRAINIG == old);
}
This is lock free and quite efficient if you have many cores, many producers and/or many consumers. The problem with this, that is also the problem with using bool, is that there are no wait semantics. Both the Producer and the Consumer will have to spin looking for FREE and respectively READY slots. You can overcome this by adding 'ready' and 'free' events. Also you need to take care of ensuring the ring buffer write/read positions are properly maintained.