I need to give a PWM output through a special output on my machine. I was just wondering how I could achieve something similar to thread.sleep but with the resolution of microseconds?
I am not sure why you want to rely on a so short period of time. You should bear in mind that the accuracy at these intervals is not too good and is even conditioned even by the CPU of the given machine. Thus, in any case you should thoroughly test the given approach under the given conditions to make sure that it delivers exactly what you want.
The smallest time value supported by .NET is a Tick (one hundred nanoseconds, as explained in this MSDN article) and thus you can build your own "sleep method" dealing with microseconds. Sample code:
Dim count As Integer = 0
Dim sw As Stopwatch = New Stopwatch
Dim microSeconds As Integer = 5
sw.Start()
Do While (sw.ElapsedTicks < 10 * microSeconds)
Loop
sw.Stop()
Related
Some sub's in my VB.Net program take a lot of time, and I do not understand why. I'd like to start a counter at the beginning of the sub and write the Milliseconds passed for each row in the console.
I tried using a Timer and resetting it after each row but it was too threadintesive. Is there a better way, using the system date/time in order to get a quite precise reading of the time each step takes?
Thank you
Use the Stopwatch class. However doing so for each row seems a bit impossible... That means you would have to add for example Console.WriteLine() after every row.
Example usage:
Dim sw As New Stopwatch
sw.Start()
yourMethod()
sw.Stop()
Console.WriteLine(String.Format("{0} ms", sw.Elapsed.TotalMilliseconds))
I'm using VB.net 2013 and SQL server 2008R2.
I'm writing a financial application , and I'm not sure about which data type to use.
I know that decimal is more precise than float , but I read that using decimal can significantly decrease the speed of calculations , so the speed of my application.
I read that using decimals can be 20 times slower than using float.
Is this true , and if yes is there a solution or should I continue to use float ?
Thank you !
Use decimal for financial applications, period. Speed does not matter in this case. When money is lost, your users won't be happy. You cannot argue saying "well, but on the other hand, it was fast". Regarding 20 times difference on float vs decimal, trust me, you won't feel it at all, there will be more major factors in your app's performance. Most likely trying to synchronize transactions between each other, DB locks etc.
EDIT: Regarding 20 times performance difference, this is true, I was able to reproduce with below code:
Module Module1
Sub Main()
Dim f As Single = 123456792.0F
Dim fsw As New Stopwatch
fsw.Start()
For i = 1 To 100000000
f *= 1.00000012F
Next
fsw.Stop()
Dim dsw As New Stopwatch
dsw.Start()
Dim d As Decimal = 123456792.0F
For i = 1 To 100000000
d *= 1.00000012F
Next
dsw.Stop()
Console.WriteLine(f)
Console.WriteLine("Float (ms): " & fsw.ElapsedMilliseconds)
Console.WriteLine(d)
Console.WriteLine("Decimal (ms): " & dsw.ElapsedMilliseconds)
Console.WriteLine("Float is " & dsw.ElapsedMilliseconds / fsw.ElapsedMilliseconds & " faster")
Console.ReadLine()
End Sub
End Module
Output:
While writing this code, I got anywhere between 10-20 times for different numbers. As I mentioned before, speed is not the concern, compare the accuracy of both approaches, notice how float is off by several orders of magnitude. This is, of course, a synthetic example, but it shows how people may end up with 1 dollar on their payroll instead of a 1000 - imagine the reaction.
I am developing an application that is very very time critical. I want to put a log writer in the code so that i can track the events and find out where the application is wasting the time.But the problem is that vb.net tells the time only at a interval of 15.25 milliseconds what to do. although msdn documentation says that we can get the time in millisecond.
To understand my problem better pls go through the following code. this code is written on a click event of a button and it writes down the time in a log file.
the problem is that it writes time like 16,16,16 and after some time when the dx value reaches to say 5000 it jumps to 31 and then to 46 and so on. Can anyone explain.
dx = 1
While dx <= 100000
dx = dx + 1
SRLog1.WriteLine("dx vALUE > " & CStr(dx) & " Ticks -> " + CStr(Now.Millisecond))
End While
You can create an incremental clock with much higher resolution by using the Stopwatch class. For example:
Dim sw = Stopwatch.StartNew()
Dim start = sw.Elapsed
'' Do stuff
'' ...
Dim sample = sw.Elapsed
Console.WriteLine(sample - start)
This is still not likely to work out that well for the code in your snippet, incrementing an integer takes less than half a nanosecond. You'll actually measure how long it takes to log, that ought to be slow enough to get different output values.
If you want to find out which parts of your application are waisting time, then you should try using a profiler. Two possible products would be JetBrains dotTrace and RedGates ANTS. You should also take a look at this question here.
This loop takes forever to run as the amount of items in the loop approach anything close to and over 1,000, close to like 10 minutes. This needs to run fast for amounts all the way up to like 30-40 thousand.
'Add all Loan Record Lines
Dim loans As List(Of String) = lar.CreateLoanLines()
Dim last As Integer = loans.Count - 1
For i = 0 To last
If i = last Then
s.Append(loans(i))
Else
s.AppendLine(loans(i))
End If
Next
s is a StringBuilder. The first line there
Dim loans As List(Of String) = lar.CreateLoanLines()
Runs in only a few seconds even with thousands of records. It's the actual loop that's taking a while.
How can this be optimized???
Set the initial capacity of your StringBuilder to a large value. (Ideally, large enough to contain the entire final string.) Like so:
s = new StringBuilder(loans.Count * averageExpectedStringSize)
If you don't specify a capacity, the builder will likely end up doing a large amount of internal reallocations, and this will kill performance.
You could take the special case out of the loop, so you wouldn't need to be checking it inside the loop. I would expect this to have almost no impact on performance, however.
For i = 0 To last - 1
s.AppendLine(loans(i))
Next
s.Append(loans(last))
Though, internally, the code is very similar, if you're using .NET 4, I'd consider replacing your method with a single call to String.Join:
Dim result as String = String.Join(Envionment.NewLine, lar.CreateLoanLines())
I can't see how the code you have pointed out could be slow unless:
The strings you are dealing with are huggggge (e.g. if the resulting string is 1 gigabyte).
You have another process running on your machine consuming all your clock cycles.
You haven't got enough memory in your machine.
Try stepping through the code line by line and check that the strings contain the data that you expect, and check Task Manager to see how much memory your application is using and how much free memory you have.
My guess would be that every time you're using append it's creating a new string. You seem to know how much memory you'll need, if you allocate all of the memory first and then just copy it into memory it should run much faster. Although I may be confused as to how vb.net works.
You could look at doing this another way.
Dim str As String = String.Join(Environment.NewLine, loans.ToArray)
So I'm kind of new to VB and am just playing around with a little project, I currently need a loop that is constantly checking the systems clock to see if it's equal to a certain time.
While Not myTime.Hour = 24
If TimeOfDay = newTime Then
nfi.ShowBalloonTip(15)
intRandNumb = RandomNumber(1, 15)
dblAddMinutes = intTime + intRandNumb
newTime = TimeOfDay.AddMinutes(dblAddMinutes)
End If
End While
I have this right now, but obviously it's grinding everything to a halt and using 50% of my cpu in the process, I just would like to know what I can substitute in or change to make this loop run better and perform how I need it to.
you can add
Threading.Thread.Sleep(0),
this will cause a context switch and greatly reduce the CPU usage
Also consider using a timer object to be called every 10 or 100 ms, this will also be better in usage then having a loop
You can use
Threading.Thread.Sleep(0)
This will cause the working thread to yield the rest of it's current timeslice which will reduce the cpu usage quite a bit. However you should consider whether you really nead busy waiting for the time or if you could get away with setting a timer to count down the difference between the current time and the expected time, e.g.:
var t = new System.Timers.Timer((DateTime.Now - DateTime.Now).TotalMilliseconds);
t.Elapsed = DoSomething;
t.Start();
checking the systems clock to see if it's equal to a certain time.
There are two "correct" ways to do this:
Build a normal app that doesn't care what time it is, and set it up in windows as a schedule task.
Check the time once and calculate how long until the desired time. Then set up a timer to wait for that exact duration.
Under no circumstance should you keep polling the system clock for something like this that will just run once.
As Joel pointed out, you should try using a timer instead. I'm not sure if your app is a form or console or other, so I'll try to be generic and use System.Timers.Timer.
The code here (interval is set at 10ms, change to a value of your need):
Private timer1 As System.Timers.Timer
Const interval As Integer = 10
Sub initTimer()
timer1 = New System.Timers.Timer(10)
AddHandler timer1.Elapsed, AddressOf Me.timer_Elapsed
timer1.Start()
End Sub
Sub timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
'do your stuff here
'Console.WriteLine(e.SignalTime.ToString())
End Sub