Piece of code that can kill computer performance [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm searching for code in c# that can kill computer performance (CPU performance, maybe cpu - memory link performance too) as much as it is possible (it will run on 4 core box so I'm going to create 4 threads and run it simultaneously).
Should it work on int / double / numeric data type / should it have some crazy data structures (but it should not take too much memory) .
Do you have any suggestions ?

Calculate PI using all processors.

You could use parallel Linq to generate a Mandelbrot (Jon Skeet has the code readily available).

Have a program that writes copies of its executable to the drive multiple times for each thread. Have each of these copies of the program then triggered by the program. :)

If you want to kill a machine's performance, try hitting the disk, because IO interrupts tend to affect everything even on a good CPU scheduler. Something like enumerating a directory of many little files, or writing a lot of big files to disk would do the trick.

Why re-invent the wheel? Use existing Load Testing software.

Calculate a long sequence of prime numbers. The following link contains code that can be modified to do this..
Program to find prime numbers

Call Bitmap.GetPixel, in a loop, in an image processing application.

I would say: a naieve (brute force) travelling salesman implementation:
(from wikipedia):
The Travelling Salesman Problem (TSP) is an NP-hard problem in combinatorial optimization studied in operations research and theoretical computer science. Given a list of cities and their pairwise distances, the task is to find a shortest possible tour that visits each city exactly once.

Brute force solving of N Queens (see wikipedia) for for example 64 queens.
Because a simple loop like this can be optimized away (sometimes only after a few minutes already running):
while(true) {
i++;
}

You can, as well, resolve a very long encrypted message, encrypted by a key such as 2048 bits.
That's a killer.

An open-source, multithreaded 3D modeling program rendering an extremely complex lighted scene will pound the strongest system into submission.

Okay, how about some infinite recursion in the spirit of StackOverflow?
void deathToAllRobots(int someMeaninglessValue) {
deathToAllRobots(someMeaninglessValue+1);
}

int *x;
while(1)
{
x = new int[10];
}

Related

Why doesn't C# allow an else clause on loops? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I decided to learn some Python (IronPython) syntax today. In doing so, I was impressed by a construct that it allows with its loops.
Python supports an else clause on its loops. An else on a loop basically says, "if this loop finished normally, then enter this clause".
Allow me to demonstrate using C#.
This code:
Something something = SomeCallToSetThisUp();
bool isCompatable = false;
foreach (Widget widget in widgets)
{
isCompatable = widget.IsCompatableWithSomething(something);
if (!isCompatable)
break;
}
if (isCompatable)
compatableSomethings.Add(something);
could become this code (not valid C#):
Something something = SomeCallToSetThisUp();
foreach (Widget widget in widgets)
{
if (!widget.IsCompatableWithSomething(something));
break;
}
else
compatableSomethings.Add(something);
Having never seen this, it struck me as cool. And once you learn it, it seemed as readable as any code I have seen.
While not universally needed (sometimes you want to affect every item in the list), I do think that it would be useful.
So, my question is: Why isn't this in C#?
I have a few ideas why:
break can make debugging harder, so the designers did not want to encourage it.
Not everything that is shiny can make it into the language. (limited scope).
But those are just guesses. I am asking for an actual canonical reason.
The usual answer is because no-one asked for it or the cost of developing and maintaining it outweights the benefits.
From Eric Lippert's blog:
I've already linked several times to Eric Gunnerson's great post on
the C# design process. The two most important points in Eric's post
are: (1) this is not a subtractive process; we don't start with C++ or
Java or Haskell and then decide whether to leave some feature of them
out. And (2) just being a good feature is not enough. Features have to
be so compelling that they are worth the enormous dollar costs of
designing, implementing, testing, documenting and shipping the
feature. They have to be worth the cost of complicating the language
and making it more difficult to design other features in the future.
After we finished the last-minute minor redesigns of various parts of
C# 3.0, we made a list of every feature we could think of that could
possibly go into a future version of C#. We spent many, many hours
going through each feature on that list, trying to "bucket" it. Each
feature got put into a unique bucket. The buckets were labelled:
Pri 1: Must have in the next version
Pri 2: Should have in the next version
Pri 3: Nice to have in the next version
Pri 4: Likely requires deep study for many years before we can do it
Pri 5: Bad idea
Obviously we immediately stopped considering the fours and fives in
the context of the next version. We then added up the costs of the
features in the first three buckets, compared them against the design,
implementation, testing and documenting resources we had available.
The costs were massively higher than the resources available, so we
cut everything in bucket 2 and 3, and about half of what was in bucket
1. Turns out that some of those "must haves" were actually "should haves".
Understanding this bucketing process will help when I talk about some
of the features suggested in that long forum topic. Many of the
features suggested were perfectly good, but fell into bucket 3. They
didn't make up the 100 point deficit, they just weren't compelling
enough.
http://blogs.msdn.com/b/ericlippert/archive/2008/10/08/the-future-of-c-part-one.aspx
Additionally, you need to weight if the feature will be easily understood by existing / new developers. IMHO else on loop is not very readable, especially since the keyword for 'execute this block if the previous one finished OK' is finally.
What is more, I think Enumerable.Any / Enumerable.All methods are much better in this scenarios.
Looping through a collection and checking a condition are different things, so they should be separate language constructs.
Because for else loops are a hack from languages like python. If you feel like you need a for else loop, you should probably put that code in a separate function.

C# Programming Best Practices For Mathematical Calculations [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Can anyone let me know where can I read the best practices to write an application that relies heavily on mathematical calculations? For example, suppose I was asked to write a C# application that generates 100 even numbers. I would write the following:
public void GenerateEven() {
for (int i=0;i<100;i++) {
Console.WriteLine(i * 2);
}
}
However that is not the best practice to do. The best way to generate even number would be, for example:
public void GenerateEven() {
int i=0;
while (i <200) {
if (i % 2 == 0) {
Console.Writeline(i);
}
}
}
If you're after expressiveness, take a page from functional programming:
public static IEnumerable<int> EvenNumbers(int start = 0)
{
while (true)
{
yield return start;
start += 2;
}
}
Then to get your sequence:
var firstHundredEvenNumbers = EvenNumers().Take(100);
It really depends upon your goal. If you're looking for composition, the above is great. If you're looking for raw speed, then you should mash all the logic into one ball and tune the heck out of it -- but it'll be harder to work with.
What makes you think the second method is the best way to do it? If I were asked to do that problem, then I would do this, so I only loop 100 times.
for (int i = 0; i < 200; i += 2)
Console.WriteLine(i);
As for your more general question, there is no one document or book that gives you best practices on how you should form loops or approach mathematical problems. This is where a computer science education comes in handy to analyze your problem and try to find an optimal solution.
In your sample problem each one of the solutions proposed (including the ones proposed by me) come down to a big O of N, so the computational differences between these solutions are negligible. The growth is linear with respect to N. The only advantage my solution provides is that it only loops over the necessary items to generate the output, instead of skipping items that do not meet the criteria.
Actually you may be looking for The Art of Computer Programming by Donald Knuth
Its called the bible of all fundamental algorithms and contains many kinds of programming algorithms and their analysis. But it does not cover any language specific moments.
If you want to generate numbers, you can use Enumerable.Range thus:
Edit: (rotem)
var a = Enumerable.Range(1,100/ 2+ 1).Select((X) => X * 2).ToList();

Store huge data in metro app [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I would like to store world cities in a list since metro app can't have local database but I am not sure it is possible (I've found a text file with more than 3 million cities).
I wonder how they did in the weather app. Since there is no latentcy in the results suggested (in the search charm or in the "favorite places" screen), I don't think they use a webservice, and also I want my app to be able to propose a list of cities even if there is no connection available.
Any idea ?
Simply stick it in a text file, delimited by line. This is not a large amount of data - you can likely hold it all in RAM in one go.
Using a database just for this one list seems a little overkill.
With some rough calculations, assuming names of around 20 characters each, I'm in the region of about 100MB of city data. That's not insignificant for one list in memory - granted, but it's not a lot to have to contend with.
You may even be able to use something like a Linq to Text provider.
How they may have done it in the charm is to only worry about a few cities - the favourites and whatever your location service last reported. Handling < 10 is easier than 3 million.
3 million cities might sound like a lot. But is it a lot for your Metro app?
These are very rough estimates
Let's use an average city name length of 20 unicode characters.
20 * 3 million = 60 million unicode characters.
60 million * 2 bytes per unicode character = 120 million bytes.
120 million bytes / 1024 = 117,187.5 kilobytes
117,187.5 kilobytes / 1024 = 114 megabytes
~115mb isn't exactly 'small' but depending on your other requirements - you can probably handle loading 150mb into memory. You can use whatever .NET objects you'd typically use like List and use LINQ to get the matching cities or whatever.
That's not to say this is your only option. It's just probably a viable one. There is a lot of very clever stuff you could do to avoid pulling all of it into memory at once; but if you want to eliminate/minimize lag - that's going to be your best bet.
I would suggest looking into SQLite if you need a database. Metro applications obviously do not have access to SQL Server and other Win32-based DBMS, but you could try SQLite as a lightweight alternative.
Try this: https://github.com/doo/SQLite3-WinRT
We recommend using SQLite database with LinqConnect - Devart's LINQ to SQL compatible solution which supports SQLite. You can employ LINQ and ADO.NET interfaces with our product. Starting from the 4.0 version, LinqConnect supports Windows Metro applications: http://blogs.devart.com/dotconnect/linqconnect-for-metro-quick-start-guide.html.

How to test 500 Trillion combinations in less than 6 hours of execution time [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I have a PHP script now looping through combinations of a set of arrays. I can test 6.1 Billion of the 500 Trillion total combinations in 1 hour with a simple PHP script. Is it possible to write a program in any language running on todays average PC that would be able to test all 500 Trillion combinations of multiple arrays in less than ~6 hours?
Also, I do not have the resources to use distributed or cluster computing for this task. What kind of gains could I expected converting the code to multithreaded java/c#?
Thank you
Let's start simple. Do you use threading? If not - a modern higher end Intel today has 12 hardware threads per processor. This means you get a factor of 12 from threading.
If someone gets a server specific for that he could get 24-32 hardware threads easily for relatively low cost.
If the arrays are semi static and you asume adecent graphics card, you may find having from 800 to 3000 processor cores a huge time saver. Nothing beats this - and even average CPU's have quite some core capabilities in their chips or the graphics cards these days.
500 trillion comparisons in 6 hours
=
83.3 trillion comparisons in 1 hour
=
1.4 trillion comparisons per minute
=
23.1 billion comparisons per second
Assuming you've got an Intel Core i7-2600 cpu (3.4GHz), which is 4 cores + hyperthreading = 8 cores, you'd need a per-core speed of
23.1/6 = 3.9GHz
which is at the extreme end of possibility for basic overclocking.
Once you factor in other overhead, what you want is not possible. Your cpu cannot do NOTHING BUT COMPARISONS.
If you don't have the resources then I'm afraid to say, with the numbers you want, you are buggered.
You'll need to rethink your data structures and the algorithms working on them to have any chance of completing your puzzle within the time limit - using PHP or any other language.
I know nothing about the process you want to run and maybe there is no way to achieve your goals with your current resources, but since you are asking for a language, and it is true that PHP is not the best one to tackle paralelism, I should say that Erlang is famous for that kind of achievements.

Who Writes Microsoft Support Articles? Can They Always Be Trusted? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Here is an example of the type of article I'm talking about:
http://support.microsoft.com/kb/319401
I assume these articles are written by people who work for Microsoft and that the code in the articles will always be rock solid and never contain any malicious code. I just want to make sure I can explain to my boss that this is an ok place to copy code from (I've been told never to copy code from the internet, but this seems like a safe source).
I would trust them not to be malicious, but they're not always good code. (MSDN samples are sometimes pretty awful.)
For example, here's some code in the sample you gave:
compareResult = ObjectCompare.Compare
(listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
Now, there are two issues here:
Why is it deemed valid to have a comparer with no sort order? This should be a constructor parameter, validated at the point of construction IMO.
You should not just negate the result of one comparison to perform a "reverse comparison". That breaks if the result of the first comparison is int.MinValue - because -int.MinValue == int.MinValue. It's better to reverse the arguments used to perform the original comparison.
There are other things I'd take issue with in this code, but these two should be enough to make my point.
I heartily agree with the other answers too, in terms of:
- Check the copyright / licence etc of any code you want to use
- Make sure you understand anything you want to use
Your boss probably wouldn't mind if you only copied the code into a test project that you use to test and understand the code. You can then use what you've learned to write the production code.
And while I don't think anyone outside of Microsoft knows the names of the people who write those support articles, they come from the same vendor that your toolchain does, so if you don't trust the support articles, then you can't trust the tools you've bought either.
Microsoft Knowledgebase articles show safe (as in non-malicious but not necessarily secure) code, but usually the example provides the most basic use case possible. There's a good chance that you'll have to tweak the code a bit for it to work the way you want.
You should also pay attention to the date of the articles. For example, the article you link to is almost three years old. There's definitely a better way to handle that situation now.
Be aware that most codes in articles are there to help you understand the concepts. They are not "production ready". Learn the concepts instead and implement your own.
Have you been told not to copy code from the internet because of rights issues? If so then you don't have to worry about this Microsoft code.
I would advise you not to use any code you don't understand. If you can't say if the code is malicious or not don't use it.
MSDN and kb support articles are written by MS employees that are part of the given product's UX team (user experience). These are people who typically have a background in technical writing, but are not necessarily developers themselves (although some are). It's very common for the UX team to collaborate with developers on the product to ensure their code samples are correct. However this collaboration in my experience is one of the lowest priorities a typical MS developer has and can go ignored, and so it can at times lead to poor code getting out.
With that said, I completely agree with Carl Norum's comment. Copying code you do not understand is done at your own risk. Make sure you understand any code you place in your product!
I've always found the Microsoft articles to be of the highest quality (sadly not their products).
However, there's always the danger of a spoofing site.
Explain that you carefully read the article to understand the information in there, and only copy code that you understand.
If you don't understand the code, then even if the code is correct it may not be doing what you actually need done, thus your program will be incorrect.
You also will have a hard time debugging and maintaining code if there are parts that you don't understand.

Categories