LINQPad taking long time to execute? - dump

//LINQPad version 4.31 - for me this code takes 1 minute and 40 seconds to execute. Can anyone else //confirm / explain whats going on
var v = new {Name="jon",Age=33};
v.Age.Dump();
v.GetType().Dump();

It's instant for me with V4.38.03.
The output from v.GetType().Dump(); is quite complex due to the anonymous type. I expect something has been improved in the latest version.

Related

How should I handle Codesys SYS_TIME overflow after only 49 days?

The SYS_TIME function in ABB PLC / codesys programming returns a DWORD indicating the number of milliseconds since the PLC was turned on. (or perhaps hard reset / other event? Cannot find documentation of this.)
The max size of a DWORD in Codesys is 232-1 = 4,294,967,295.
This means SYS_TIME overflows after only 49.7 days!
Can anyone confirm exactly what the SYS_TIME function returns after 49.7 days has elapsed? Does it integer overflow and start counting from zero again?
This has important ramifications for using SYS_TIME for functions such as warning how long it is since some event occurred. (e.g. a read of a remote device via modbus).
Assuming it is just an integer overflow and SYS_TIME resets to zero, then the programmer can deal with this by e.g. resetting the variable they are using to record the last known event time:
(* Assuming now, last_event_time are suitably declared DWORDs *)
now := SYS_TIME(TRUE);
IF last_event_time > now THEN
last_event_time := 0;
END_IF
(* continue, performing check of how long since last event occurred etc.... *)
I'm hoping there is something I have missed that offers an alternative approach.
However - This is a GOTCHA that could trip up a PLC programmer who hadn't thought of this, causing an apparently fully functioning PLC program that has been tested extensively to fail after 49 days of use in the field.
Would be very helpful if there was an alternative to SYS_TIME that returns an LWORD, good for 5 billion years of uninterrupted service :-)
NB - I believe this function may be specific to the ABB AC500 range of PLCs, rather than a standard Codesys function, so this question is mostly directed at ABB & ABB PLC programmers.
There are few options, but I would use either one of the following
Read system date and time and keep it updated. You will get 1 second resolution when using DT. It's easy to do comparison between DTs when you convert them to DWORD first (epoch time). See my old answer for Codesys time update. Note that if you calculate something like DT1-DT2, you will get a result of TIME -> Same overflow problem is possible. That's why DT_TO_DWORD would be good idea.
Make your own time. Your PLC has a cycle time, that should always be precise the same. Use it for you calculation.
This is a simple example with different data types.
Note that it's also possible to read cycle time using some Codesys library if required, not sure which one though. See for example this.
PROGRAM PRG_Time
VAR CONSTANT
TASK_CYCLE_TIME_MS : WORD := 10; //Update this!
END_VAR
VAR_OUTPUT
Total : LREAL;
TotalMilliseconds : LWORD;
TotalSeconds : DWORD;
Milliseconds : WORD;
END_VAR
Total := Total + TASK_CYCLE_TIME_MS / 1000.0;
TotalMilliseconds := TotalMilliseconds + TASK_CYCLE_TIME_MS;
Milliseconds := Milliseconds + TASK_CYCLE_TIME_MS;
//Calculate seconds
IF Milliseconds >= 1000 THEN
TotalSeconds := TotalSeconds + 1;
Milliseconds := Milliseconds - 1000;
END_IF
The LREAL is precise enough for milliseconds. So basically here is a SYS_TIME as LWORD (the TotalMilliseconds)
Looking further into this, I have confirmed two things:
SYS_TIME is definitely an ABB AC500 specific function, included in library SysInt_AC500_V10.lib.
Quote from the online help for ABB AC500: "An overflow is reached after 49 days. After this, the counter restarts at 0.". So that answers the part about the behaviour of the function.
The second part of my question (what is the best way of handling this?) remains open...

Schedule function execution in swift

I'm developing a simple app in Swift and I need to schedule a function execution every 24 hours. I'm aware of the method:
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
that could solve my problem but, is this the right solution for a 24 hours delay?
Thanks
Theoretically, this is possible.
The problem is that your app would have to run in the foreground for 24 hours, which is very unlikely to happen. Unfortunately, you can not run background tasks just like that.
The solution:
Just make it look like the function would execute in the background. Every time the update function is called, simply save the Int(Date().timeIntervalSince1970) to UserDefaults. This works like a timestamp and saves the last time you called your update function. Every time in the viewDidLoad()-function (not sure if it's called the same on Mac apps, but you can imagine what I mean) call:
If let timestamp = UserDefaults.standard.integer(forKey: "yourTimestampKey") {
let currentTimestamp = Date().timeIntervalSince1970
if (currentTimestamp - timestamp) > 86400 { // number of seconds in 24 hours
// the last time your function was updated was at least 24h ago
update()
}
}
That's how you can make it appear like it was updated in the background. I use this all the time in my apps and it works perfectly.
EDIT:
Maybe, just in case the app does indeed run 24 hours in a row, I would set up the upper function that you posted first as well.

EF6/Code First: Super slow during the 1st query, but only in Debug

I'm using EF6 rc1 with Code First strategy, without precompiled views and the problem is:
If I compile and run the exe application it takes like 15 seconds to run the first query (that's okay, since I'm still working on the pre-generated views). But if I use Visual Studio 2013 Preview to Debug the exact same application it takes almost 2 minutes BEFORE running the first query:
Dim Context = New MyEntities()
Dim Query = From I in Context.Itens '' <--- The debug takes 2 minutes in here
Dim Item = Query.FirstOrDefault()
Is there a way to remove this extra time? Am I doing something wrong here?
Ps.: The context itself is not complicated, its just full with 200+ tables.
Edit: Found out that the problem is that during debug time the EF appears to be generating the Views ignoring the pre-generated ones.
Using the source code from EF I discovered that the property:
IQueryProvider IQueryable.Provider
{
get
{
return _provider ?? (_provider = new DbQueryProvider(
GetInternalQueryWithCheck("IQueryable.Provider").InternalContext,
GetInternalQueryWithCheck("IQueryable.Provider").ObjectQueryProvider));
}
}
is where the time is being consumed. But this is strange since it only takes time in debug. Am I missing something here?
Edit: Found more info related to the question:
Using the Process Monitor (by Sysinternals) I found out that there its the 'desenv.exe' process that is consuming tons of time. To be more specific its consuming time with an 'Thread Exit'. It repeats the Thread Exit stack 36 times. I don't know if this info is very useful, but I saved a '.cvs' with the stack, here is his body: [...] (edit: removed the '.cvs' body, I can post it again by the comments if someone really think its going to be useful, but it was confusing and too big.)
Edit: Installed VS2013 Ultimate and Entity Framework 6 RTM. Installed the Entity Framework Power Tools Beta 4 and used it to generate the Views. Nothing changed... If I run the exe it takes 20 seconds, if I 'Start' debugging it takes 120 seconds.
Edit: Created a small project to simulate the error: http://sdrv.ms/16pH9Vm
Just run the project inside the environment and directly through the .exe, click the button and compare the loading time.
This is a known performance issue in Lazy (which EF is using) when the debugger is attached. We are currently working on a fix (the current approach we are looking at is removing the use of Lazy). We hope to ship this fix in a patch release soon. You can track progress of this issue on our CodePlex site - http://entityframework.codeplex.com/workitem/1778.
More details on the coming 6.0.2 patch release that will include a fix are here - http://blogs.msdn.com/b/adonet/archive/2013/10/31/ef6-performance-issues.aspx
I don't know if you have found the solution. But in my case, I had similar issue which wasted me close to a week after trying different suggestions. Finally, I found a solution by changing my web.config to optimizeCompilations="true" and performance improved dramatically from 15-30 seconds to about 2 seconds.

Matlab help, doc commands very slow

I can't put my finger on why it's doing this, but since a few days help takes a lot of time to show. Either inline (selecting a function, selecting "help for"), or by using the commands doc or help. The command doc cmdname takes about 10 seconds to show the help window. I did, taking fwrite as example, try profile on;doc fwrite;profile viewer and digging through the rabbit hole I arrived on a private java matlab method which is taking forever:
tic;
com.mathworks.mlwidgets.help.HelpUtils.getDocCommandArg('matlab\fwrite', true);
toc
Elapsed time is 9.993832 seconds.
Any idea what could be causing that issue? It also happens in safe mode, with no other running programs than MATLAB. I'd try a complete reinstall of MATLAB, but if I could avoid that that'd be great.
There are a couple of things that might be contributing to this issue, but given the information you've provided it's hard to say exactly what is going on.
When the R2012b help system initializes, it does a few tasks that can sometimes introduce a noticeable delay, mostly related to determining which MathWorks products are available and how you have your help preferences set up. 10 seconds would be unusual, but there is a possibility that this is what's causing the delay. If you're seeing the performance hit on your first use of the help system, but not again in the same MATLAB session, this is the likely cause. This behavior is improved in R2013a.
Other than initialization tasks, the Java call in question is a relatively straightforward search against the same search index that is used for searching the documentation. If you are finding that searching the documentation in the help browser is slow, this would be a hint that the performance issue lies somewhere within the help system's search functionality.
In either case, your best bet is probably to contact MathWorks technical support. It is likely that we can take a closer look at this and possibly come up with some sort of fix.
The problem has been solved with input from mathworks support:
>> tic;doc fwrite;toc
Elapsed time is 20.301202 seconds.
>> tic;reader = org.apache.lucene.index.IndexReader.open(fullfile(docroot,'helpsearch'));
searcher = org.apache.lucene.search.IndexSearcher(reader);
term = org.apache.lucene.index.Term('relpath','ref/plot.html');
query = org.apache.lucene.search.TermQuery(term);
hits = searcher.search(query);
fprintf('Found %d results\n', hits.length); searcher.close; reader.close; toc;
Java exception occurred:
java.io.IOException: Lock obtain timed out:
Lock#C:\Users\b\AppData\Local\Temp\lucene-ca3070c312bc20732565936b371a8bd3- commit.lock
at
org.apache.lucene.store.Lock.obtain(Lock.java:56)
at
org.apache.lucene.store.Lock$With.run(Lock.java:98)
at
org.apache.lucene.index.IndexReader.open(IndexReader.java:141)
at
org.apache.lucene.index.IndexReader.open(IndexReader.java:125)
After that, thinking it was a problem with a temp file being locked, I closed Matlab, went into AppData\Local\Temp\ and cleaned all the temporary files in it.
>> tic;
reader = org.apache.lucene.index.IndexReader.open(fullfile(docroot,'helpsearch'));
searcher = org.apache.lucene.search.IndexSearcher(reader);
term = org.apache.lucene.index.Term('relpath','ref/plot.html');
query = org.apache.lucene.search.TermQuery(term);
hits = searcher.search(query);
fprintf('Found %d results\n', hits.length); searcher.close; reader.close; toc;
Found 5 results
Elapsed time is 0.106868 seconds.
>> tic;doc fwrite;toc
Elapsed time is 0.153808 seconds.
Either it's the cleaning the temp files or the reference to internal java classes org.apache.lucene* that did the trick, but here it is, now doc is fast again.

How to round the minute of a timestamp to increments of 15?

I'm building an application to record when my cat has an asthma attack. I'm not interested in the exact time since glancing at the time in interval of 15 minutes is easier to review (e.g. rounding 9:38am should be recorded as 9:45am).
I looked for a UDF at cflib.org for this but couldn't find one. I tinkered with CF's round function but I'm not getting it to do what I want.
Any advice?
This could do with a bit more polish (like data type validation) but it will take a time value and return it rounded to the nearest 15-minute increment.
<cfscript>
function roundTo15(theTime) {
var roundedMinutes = round(minute(theTime) / 15 ) * 15;
var newHour=hour(theTime);
if (roundedMinutes EQ 60) {
newHour=newHour + 1;
roundedMinutes=0;
}
return timeFormat(createTime(newHour,roundedMinutes,0),"HH:mm");
}
</cfscript>
I'm not familiar with the format of the timestamp here, but generally when I want to round I do something like floor((val + increment / 2) / increment) * increment
I like Al Everett's answer, or alternatively store the actual time to preserve the most accurate time, then use query of query in the view and use between :00 and :15 to show the time in 15min period.
If you use Henry's suggestion to store the precise time in the database (principle: if there's no cost, prefer to preserve data), then you can simply use Al Everett's rounding function whenever you display the data to the user.