I'm new to programming, and I became stuck here where I have to write an algorithm and pseudo code for this flowchart, but I'm confused on how to do the loop delay 2 seconds, or the add 2 seconds until it hits 10.
Thanks for your help!!!!
I think that psuedocode can sometimes be harder than writing real code for people who are just starting. The psuedocode for those instructions can be pretty-well exactly as in the flowchard:
How to do the loop delay 2 seconds:
while (door_sensor_read is no)
sleep for 2 seconds
and the add 2 seconds until it hits 10:
The pseudo code would be:
while (counter < 10)
{
sensor read = read the door;
while (sensor read == closed)
{
counter = 0;
sleep 2000ms;
}
counter += 2;
sleep 2000ms;
}
sound alarm;
Related
The following code to find prime numbers greatly differs between Adobe ColdFusion (10) and Lucee (4.5) regarding performance. Tested on the same machine (6C i7 3930k # 4 GHz, Windows 10 64 Bit, JVM memory settings equal on both CFML engines: JDK7 -Xms512m -Xmx2048m -XX:MaxPermSize=512m):
<cfscript>
ticks = getTickCount();
stopIndex = 10000;
primes = [];
divisions = 0;
primes.add(2);
primes.add(3);
n = 5;
for (n; n < stopIndex; n += 2) {
isPrime = true;
d = 3;
for (d; d < n; d++) {
divisions++;
if (n % d == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(n);
}
}
ticks = (getTickCount() - ticks);
</cfscript>
<cfoutput>
<p>
#numberFormat(divisions)# divisions in #ticks# ms.
</p>
<p>
#numberFormat(arrayLen(primes))# prime numbers found below #numberFormat(stopIndex)#.
</p>
</cfoutput>
stopIndex # 10k
ACF: 280 ms
LUC: 1300 ms
stopIndex # 20k
ACF: 1000 ms
LUC: 4800 ms
stopIndex # 30k
ACF: 2200 ms
LUC: 10500 ms
trycf.com and cflive.net show a similar gap.
I checked if cfscript (vs. tags) has impact on the time, it doesn't. CFML engine related server settings do not seem to have any noticable impact either.
What could be the reason for the performance difference?
And how could I possibly resolve this?
Background: I'm running heavy math ops (geometry, image rendering)) on a production server, which happens to be running Lucee, and noticed the sluggish performance.
Integer maths is slower than floating point maths, so this runs slower because of the way that Lucee stores variables as types. if you force the n to be non integer Lucee runs 4x faster
if ((n+1.0) % d == 0) {
This tweak also more than doubles the speed in ACF too
https://luceeserver.atlassian.net/browse/LDEV-1541
I think the performance issue side of things is down to Lucee to fix, rather than you and your code.
However from the perspective of overall performance of this particular algorithm, they best economy you can make is to loop to sqr(n)+1 rather than all the way to n. You're doing way more work than you need to be, and that's a bigger contributor to the performance of this code than the platform differences.
Also you only need to loop over the preceding primes, not every (second) number. That'd improve your performance further.
I realise the algorithm is just an example, but in all honesty the rest of it isn't something yer likely to be able to fix. Raise a ticket with Lucee and wait for it to be fixed (or DIY, if you have the time / Java knowledge).
I know this is not answering the question, but taking Adam's comment further, it doesn't even have to be up to the square root. Once you realize a number isn't divisible by 3, you can limit your top to the results of the division by 3. Tracking previous prime numbers takes memory when your n becomes large. If you can afford that, that's great. If you can't, then incrementing the denominator by 2 would speed it up by 2 since you're skipping even numbers. This code is about 50 times faster:
<cfscript>
ticks = getTickCount();
stopIndex = 10000;
primes = [];
divisions = 0;
primes.add(2);
primes.add(3);
n = 5;
for (n; n < stopIndex; n += 2) {
isPrime = true;
d=3;
n2=n;
for (d; d < n2; ) {
divisions++;
Result=n/d;
if (Result eq Int(Result)) {
isPrime = false;
break;
} else {
d+=2;
n2=Result;
}
}
if (isPrime) {
primes.add(n);
}
}
ticks = (getTickCount() - ticks);
</cfscript>
56,570 divisions in 32 ms (vs. 1500 before on my machine)
1,229 prime numbers found below 10,000.
I have a program I am trying to parallelize using OpenMP - it makes a very large loop over some data. Since incrementing a shared variable (so I can report progress as it goes) is somewhat of an issue, I thought I'd break the loop up into smaller chunks, loop over those multiple times, and just report the status at the end of/outside the openmp loop.
Problem is, before the OpenMP for loop starts for the 3rd time, the program locks up. Just sits there, does nothing. I've stripped out all but the simplest code. Here it is:
some other variable declarations for removed code above here
int dbl = 0;
int lasttime = 0;
int seedbase = 0;
const char *pl = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const double mm = 62.0 / 2147483647.0;
for(dbl = 0; dbl < 2048 && !abort; dbl++) {
seedbase = dbl; //(dbl * 2097152) - 2147483648;
printf("Loop %d %d\n", dbl, abort);
#pragma omp parallel for private(seed) shared(dbl)
for(seed = 0; seed < 20971; seed++) { //52
if(dbl == 2)
printf("oo\n");
}
if(abort)
break;
lasttime = time();
hps = (double)((dbl*2097152) * clk_tck) / (double)((times(&tms) - start_time));
printf("So far: %0.2fsec (%0.2fhps) %0.2f sec left\n", (double)(times(&tms) - start_time) / (double)clk_tck, hps, (((long)1 << 32) - (dbl * 2097152)) / hps);
}
}
When compiled and run, I get:
Loop 0 0
So far: 0.02sec (0.00hps) inf sec left
Loop 1 0
So far: 0.02sec (104857600.00hps) 40.94 sec left
Loop 2 0
^C
Loop 0 starts, and the openmp runs (and does nothing) then exits, and the "So far:" is printed.
Loop 1 starts, same thing.
Loop 2 starts, and everything hangs. The printf("oo"); never happens. If I change the line to be if(dbl <= 2) my screen fills with looped "oo"'s as the loop runs.
But before the seed loop ever happens the third time - it's dead. Just sits there chewing up CPU time doing nothing.
Can you not quickly loop over a openmp loop? Is that the issue? I find it odd it's ALWAYS stopping before the 3rd run, regardless of how complex the code inside the seed loop is (I removed 200 lines of code - it had no effect)
Is there any way to compute the time complexity of an algorithm programatically? For example, how could I calculate the complexity of a fibonacci(n) function?
The undecidability of the halting problem says that you can't even tell if an algorithm terminates. I'm pretty sure from this it follows that you can't generally solve the complexity of an algorithm.
While it's impossible to do for all cases (unless you run your own code parser and just look at loops and what impacts on their values and such), it is still possible to do as a black box test with an upper bound time set. That is to say, have some variable that is set to determine that once a program's execution passes this time it's considered to be running forever.
From this your code would look similar to this (quick and dirty code sorry it's a little verbose and the math might be off for larger powers I haven't checked).
It can be improved upon by using a set array of input values rather than randomly generating some, and also by checking a wider range of values, you should be able to check any input versus any other two inputs and determine all the patterns of method duration.
I'm sure there are much better (namely more accurate) ways to calculate the O between a set of given numbers than shown here (which neglects to relate the run time between elements too much).
static void Main(string[] args)
{
var sw = new Stopwatch();
var inputTimes = new Dictionary<int, double>();
List<int> inputValues = new List<int>();
for (int i = 0; i < 25; i++)
{
inputValues.Add(i);
}
var ThreadTimeout = 10000;
for (int i = 0; i < inputValues.Count; i++)
{
int input = inputValues[i];
var WorkerThread = new Thread(t => CallMagicMethod(input)) { Name = "WorkerThread" };
sw.Reset();
Console.WriteLine("Input value '{0}' running...", input);
sw.Start();
WorkerThread.Start();
WorkerThread.Join(ThreadTimeout);
sw.Stop();
if (WorkerThread.IsAlive)
{
Console.WriteLine("Input value '{0}' exceeds timeout", input);
WorkerThread.Abort();
//break;
inputTimes.Add(input, double.MaxValue);
continue;
}
inputTimes.Add(input, sw.Elapsed.TotalMilliseconds);
Console.WriteLine("Input value '{0}' took {1}ms", input, sw.Elapsed.TotalMilliseconds);
}
List<int> indexes = inputTimes.Keys.OrderBy(k => k).ToList();
// calculate the difference between the values:
for (int i = 0; i < indexes.Count - 2; i++)
{
int index0 = indexes[i];
int index1 = indexes[i + 1];
if (!inputTimes.ContainsKey(index1))
{
continue;
}
int index2 = indexes[i + 2];
if (!inputTimes.ContainsKey(index2))
{
continue;
}
double[] runTimes = new double[] { inputTimes[index0], inputTimes[index1], inputTimes[index2] };
if (IsRoughlyEqual(runTimes[2], runTimes[1], runTimes[0]))
{
Console.WriteLine("Execution time for input = {0} to {1} is roughly O(1)", index0, index2);
}
else if (IsRoughlyEqual(runTimes[2] / Math.Log(index2, 2), runTimes[1] / Math.Log(index1, 2), runTimes[0] / Math.Log(index0, 2)))
{
Console.WriteLine("Execution time for input = {0} to {1} is roughly O(log N)", index0, index2);
}
else if (IsRoughlyEqual(runTimes[2] / index2, runTimes[1] / index1, runTimes[0] / index0))
{
Console.WriteLine("Execution time for input = {0} to {1} is roughly O(N)", index0, index2);
}
else if (IsRoughlyEqual(runTimes[2] / (Math.Log(index2, 2) * index2), runTimes[1] / (Math.Log(index1, 2) * index1), runTimes[0] / (Math.Log(index0, 2) * index0)))
{
Console.WriteLine("Execution time for input = {0} to {1} is roughly O(N log N)", index0, index2);
}
else
{
for (int pow = 2; pow <= 10; pow++)
{
if (IsRoughlyEqual(runTimes[2] / Math.Pow(index2, pow), runTimes[1] / Math.Pow(index1, pow), runTimes[0] / Math.Pow(index0, pow)))
{
Console.WriteLine("Execution time for input = {0} to {1} is roughly O(N^{2})", index0, index2, pow);
break;
}
else if (pow == 10)
{
Console.WriteLine("Execution time for input = {0} to {1} is greater than O(N^10)", index0, index2);
}
}
}
}
Console.WriteLine("Fin.");
}
private static double variance = 0.02;
public static bool IsRoughlyEqual(double value, double lower, double upper)
{
//returns if the lower, value and upper are within a variance of the next value;
return IsBetween(lower, value * (1 - variance), value * (1 + variance)) &&
IsBetween(value, upper * (1 - variance), upper * (1 + variance));
}
public static bool IsBetween(double value, double lower, double upper)
{
//returns if the value is between the other 2 values +/- variance
lower = lower * (1 - variance);
upper = upper * (1 + variance);
return value > lower && value < upper;
}
public static void CallMagicMethod(int input)
{
try
{
MagicBox.MagicMethod(input);
}
catch (ThreadAbortException tae)
{
}
catch (Exception ex)
{
Console.WriteLine("Unexpected Exception Occured: {0}", ex.Message);
}
}
And an example output:
Input value '59' running...
Input value '59' took 1711.8416ms
Input value '14' running...
Input value '14' took 90.9222ms
Input value '43' running...
Input value '43' took 902.7444ms
Input value '22' running...
Input value '22' took 231.5498ms
Input value '50' running...
Input value '50' took 1224.761ms
Input value '27' running...
Input value '27' took 351.3938ms
Input value '5' running...
Input value '5' took 9.8048ms
Input value '28' running...
Input value '28' took 377.8156ms
Input value '26' running...
Input value '26' took 325.4898ms
Input value '46' running...
Input value '46' took 1035.6526ms
Execution time for input = 5 to 22 is greater than O(N^10)
Execution time for input = 14 to 26 is roughly O(N^2)
Execution time for input = 22 to 27 is roughly O(N^2)
Execution time for input = 26 to 28 is roughly O(N^2)
Execution time for input = 27 to 43 is roughly O(N^2)
Execution time for input = 28 to 46 is roughly O(N^2)
Execution time for input = 43 to 50 is roughly O(N^2)
Execution time for input = 46 to 59 is roughly O(N^2)
Fin.
Which shows the magic method is likely O(N^2) for the given inputs +/- 2% variance
and another result here:
Input value '0' took 0.7498ms
Input value '1' took 0.3062ms
Input value '2' took 0.5038ms
Input value '3' took 4.9239ms
Input value '4' took 14.2928ms
Input value '5' took 29.9069ms
Input value '6' took 55.4424ms
Input value '7' took 91.6886ms
Input value '8' took 140.5015ms
Input value '9' took 204.5546ms
Input value '10' took 285.4843ms
Input value '11' took 385.7506ms
Input value '12' took 506.8602ms
Input value '13' took 650.7438ms
Input value '14' took 819.8519ms
Input value '15' took 1015.8124ms
Execution time for input = 0 to 2 is greater than O(N^10)
Execution time for input = 1 to 3 is greater than O(N^10)
Execution time for input = 2 to 4 is greater than O(N^10)
Execution time for input = 3 to 5 is greater than O(N^10)
Execution time for input = 4 to 6 is greater than O(N^10)
Execution time for input = 5 to 7 is greater than O(N^10)
Execution time for input = 6 to 8 is greater than O(N^10)
Execution time for input = 7 to 9 is greater than O(N^10)
Execution time for input = 8 to 10 is roughly O(N^3)
Execution time for input = 9 to 11 is roughly O(N^3)
Execution time for input = 10 to 12 is roughly O(N^3)
Execution time for input = 11 to 13 is roughly O(N^3)
Execution time for input = 12 to 14 is roughly O(N^3)
Execution time for input = 13 to 15 is roughly O(N^3)
Which shows the magic method is likely O(N^3) for the given inputs +/- 2% variance
So It is possible to programatically determine the complexity of an algorithm, you need to make sure that you do not introduce some additional work which causes it to be longer than you think (such as building all the input for the function before you start timing it).
Further to this you also need to remember that this is going to take a significant time to try a large series of possible values and return how long it took, a more realistic test is to just call your function at a large realistic upper bound value and determine if it's response time is sufficient for your usage.
You likely would only need to do this if you are performing black box testing without source code (and can't use something like Reflector to view the source), or if you have to prove to a PHB that the coded algorithms are as fast as it can be (ignoring improvements to constants), as you claim it is.
Not in general. If the algorithm consists of nested simple for loops, e.g.
for (int i=a; i<b; ++i)
then you know this will contribute (b-a) steps. Now, if either b or a or both depends on n, then you can get a complexity from that. However, if you have something more exotic, like
for (int i=a; i<b; i=whackyFunction(i))
then you really need to understand what whackyFunction(i) does.
Similarly, break statements may screw this up, and while statements may be a lost cause since it's possible you wouldn't even be able to tell if the loop terminated.
Count arithmetic operations, memory accesses and memory space used inside fibbonacci() or whatever it is, measure its execution time. Do this with different inputs, see the emerging trends, the asymptotic behavior.
General measures like cyclomatic complexity are useful in giving you an idea of the more complex portions of your code, but it is a relatively simple mechanism.
I'm trying to create a function in R that returns for the first x seconds after the function call 1, the next x seconds 0, the next x seconds 1 again,...the whole procedure should stop after another time interval or after n iterations. I want to do this with one function call.
I read about the package tcltk which apparently entails some possibilities to create such "timer" functions, however I did not find enough explanations to sort out my issue.
Could you advise me where to find a good manual that explains tcl in context with R? Do you have other ideas how to create such a function in an efficient way?
Thanks a lot for your help.
If I understood you correctly, you are trying to create a function that will return 1 whenever it is called in the first x secs, then return 0 whenever it's called in the next x secs, then return 1 over the next x secs, etc. And after a certain total time, it should be "done", maybe return -1?
You could do this using the following function that will "create" a function with any desired interval:
flipper <- function(interval=10, total = 60) {
t0 <- Sys.time()
function() {
seconds <- round(as.double( difftime(Sys.time(), t0, u = 'secs')))
if(seconds > total)
return(-1) else
return(trunc( 1 + (seconds / interval ) ) %% 2)
}
}
You can use this to create a function that alternates between 0 and 1 every 10 secs during the first 60 seconds, and returns -1 after 60 seconds:
> flp <- flipper(10,60)
Now calling flp() will have the behavior you are looking for, i.e. when you call flp() during the next 60 secs, it will alternate between 1 and 0 every 10 secs, then after 60 secs it will just return -1.
Sys.sleep from base could not be a solution?
E.g.: stop every 10th iteration in a loop for 10 seconds:
for (i in 1:100) {
# do something
if ((i %% 10) == 0) {
Sys.sleep(10)
}
}
May I also suggest:
Timer 1
library(data.table)
begin.time <- proc.time()
timetaken(begin.time)
Timer 2
library(matlab)
tic(gcFirst=FALSE)
toc(echo=TRUE)
Both are excellent choices for timers
The tcltk command after will call a function after a time delay. Getting it to repeatedly call can be done along the following lines (made more complicated by this desire to have different intervals between events).
afterID <- ""
someFlag <- TRUE
MS <- 5000 # milliseconds
repeatCall <- function(ms=MS, f) {
afterID <<- tcl("after", ms, function() {
if(someFlag) {
f()
afterID <<- repeatCall(MS - ms, f)
} else {
tcl("after", "cancel", afterID)
}
})
}
repeatCall(MS, function() {
print("Running. Set someFlag <- FALSE to stop.")
})
timefun <- function(interval = 10, output = c(0, 1)) {
start <- Sys.time()
# do some stuff
for (i in 1:99999) paste(i, i^2)
# how many intervals did it take
elapsed <- as.numeric(round(Sys.time() - start)) / interval
output[elapsed %% length(output) + 1]
}
I'm not clear on "the whole procedure should stop after another time interval or after n iterations", do you want to check elapsed time periodically during the function execution and stop() if it's above a certain value?
I'd like to print the max number of concurrent events given the start time and end time of each event in "hhmm" format (example input below)
$ cat input.txt
1030,1100
1032,1100
1032,1033
1033,1050
1034,1054
1039,1043
1040,1300
For this, I would
Sort by start time (column 1)
Use awk/sed to iterate over all values in column 2 (i.e end time) to find the count of end times preceeding this event which are greater than the current value (i.e find all
currently running events). To elaborate, assuming line 3 was being processed by awk ... Its end time is 10:33. The end times of the preceding 2 events are 11:00 and 11:00.
Since both these values are greater than 10:33 (i.e. they are still running at 10:33), the third column (i.e. number of concurrent jobs) would contain 2 for this line
The expected output of the awk script to find concurrent events for this input would be
0
1
2
2
2
4
0
Find the max value of this third column.
My awk is rudimentary at best and I am having difficulty implementing step 2.
I'd like this to be a pure script without resorting to a heavy weight language like java.
Hence any help from awk gurus would be highly appreciated. Any non-awk linux one liners are also most welcome.
BEGIN {FS="\,"; i=0}
{ superpos=0;
for (j=1; j<=i; j++ ){
if($2 < a[j,2])
++superpos
}
a[++i,1]=$1;
a[i,2]=$2;
print superpos;
a[i,3]=superpos;
}
END{ max=0;
for (j=1; j<=i; j++ ){
if ( a[j,3]>max)
max= a[j,3];
}
print "max = ",max;
}
Running at ideone
HTH!
Output:
0
0
2
2
2
4
0
max = 4
Edit
Or more awkish, if you prefer:
BEGIN {FS="\,"; max=0 }
{
b=0;
for (var in a){
if($2 < a[var]) b++;
}
a[NR]=$2;
print b;
if (b > max) max = b;
}
END { print "max = ", max }