I understand the question may not make sense at first, but I'll explain it here.  First, I have the following C++ code, a simple Hello World.  #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main() {   printf("Hello World ");   return(0); }   Now I am calling it from within Java using this:  long start = System.nanoTime(); Process p = Runtime.getRuntime().exec("/home/name/./test");   long totalTime = System.nanoTime() - start;  System.out.println("Time: " + totalTime);   After doing this a couple times i get the following output:  Time: 8155128  Time: 732204  Time: 508819  Time: 662987  I wonder if this is a correct way to measure the time for the c++ code execution and i am want to know if there is an explanation on why always the first execution shows a time 10X bigger than the others (even if it's nanoseconds)
915
How do you write (and run) a correct micro-benchmark in Java?  I'm looking for some code samples and comments illustrating various things to think about.  Example: Should the benchmark measure time/iteration or iterations/time, and why?  Related:
73742
What is the best way to handle large numeric inputs in C++ (for example 10^100)?   For algorithms I usually switch over to ruby and I sometimes use strings.  Any other good methods?
119210
Is there a c++ equivalent of Java's  try {     ... } catch (Throwable t) {     ... }   I am trying to debug Java/jni code that calls native windows functions and the virtual machine keeps crashing.  The native code appears fine in unit testing and only seems to crash when called through jni.  A generic exception catching mechanism would prove extremely useful.
17527
I am designing an implementation of RSA . I recorded computation times in Java by using System.currentTimeMillis(). It returned an encryption time of 0.05 ms and decryption time of 0.55 ms, or a ratio of 1:11.   This seems like a large difference. Is it supposed to be this way?  //here my key has 256 bits  for (;;) {             long begin = System.currentTimeMillis();              for (int i = 0; i &lt; num; i++) {              decrypt();             }              long end = System.currentTimeMillis();              long time = end - begin;              if (time &gt;= 10000) {                 System.out.printf("Average Encryption takes: %.2f ms\n",                         (double) time / num);                 break;             }              num *= 2;         }  p = BigInteger.probablePrime(128, random); q = BigInteger.probablePrime(128, random); N=(p.subtract(one)).multiply(q.subtract(one)); e=BigInteger.probablePrime(32, random); d=e.modInverse(N); private void encrypt() {  C= M.modPow(e,N);  }  private void decrypt() {     RM = C.modPow(d, N);     }
47371
Let's say I have some Java code:  public class SomeClass {     static {         private final double PI = 3.14;         private final double SOME_CONSTANT = 5.76;         private final double SOME_OTHER_CONSTANT = 756.33;     }    //rest of class }   If a thread is initializing SomeClass's Class object and is in the middle of initializing the values in the static block when a second thread wants to load SomeClass's Class again, what happens to the static block?  Does the second thread ignore it assuming it's already initialized even though the first thread is not done? Or does something else happen?
51350
I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.  What's the best way to do this?
2226
I am looking for a way to get the output of a command when it is run from within a C++ program.  I have looked at using the system() function, but that will just execute a command. Here's an example of what I'm looking for:  std::string result = system("./some_command");   I need to run an arbitrary command and get its output. I've looked at , but I have not found anything that will give me what I need.
32717
This question may sound fairly elementary, but this is a debate I had with another developer I work with.  I was taking care to stack allocate things where I could, instead of heap allocating them. He was talking to me and watching over my shoulder and commented that it wasn't necessary because they are the same performance wise.  I was always under the impression that growing the stack was constant time, and heap allocation's performance depended on the current complexity of the heap for both allocation (finding a hole of the proper size) and de-allocating (collapsing holes to reduce fragmentation, as many standard library implementations take time to do this during deletes if I am not mistaken).  This strikes me as something that would probably be very compiler dependent. For this project in particular I am using a  compiler for the  architecture. Insight on this combination would be most helpful, but in general, for GCC, and MSVC++, what is the case? Is heap allocation not as high performing as stack allocation? Is there no difference? Or are the differences so minute it becomes pointless micro-optimization.
13911
Possible Duplicate:          Here is a test case:   void foo(int i, int j) {    printf("%d %d", i, j); } ... test = 0; foo(test++, test);   I would expect to get a "0 1" output, but I get "0 0"  What gives??
46309
I just wrote the following C++ function to programatically determine how much RAM a system has installed.  It works, but it seems to me that there should be a simpler way to do this.  Can someone tell me if I'm missing something?  getRAM() {     FILE* stream = popen( "head -n1 /proc/meminfo", "r" );     std::ostringstream output;     int bufsize = 128;      while( !feof( stream ) &amp;&amp; !ferror( stream ))     {         char buf[bufsize];         int bytesRead = fread( buf, 1, bufsize, stream );         output.write( buf, bytesRead );     }     std::string result = output.str();      std::string label, ram;     std::istringstream iss(result);     iss &gt;&gt; label;     iss &gt;&gt; ram;      return ram; }   First, I'm using popen("head -n1 /proc/meminfo") to get the first line of the meminfo file from the system.  The output of that command looks like     MemTotal:       775280 kB   Once I've got that output in an istringstream, it's simple to tokenize it to get at the information I want.  My question is, is there a simpler way to read in the output of this command?  Is there a standard C++ library call to read in the amount of system RAM?
26974
Okay, so I needed to find the smallest value of n such that algorithm 100*n^2 is faster than 2^n.   [what I have tried]  So, I instantly thought '0'. But, I then realized it can't be 0, 0 implies that there are no digits being entered in the algorithm, it also implies that the program does not run or terminate.   I typed in 2^32 and got a number over 4 billion. Okay, this is good, I'm finding numbers that have 100*n^2 being faster than 2^n.   I halved that, n = 20.  I kept inserting values counting down until I got to n = 15.   I also counted up from n = 10, the answer is undoubtedly n = 15, but I have a problem . . . .I solved this using brute force and that isn't good. What if I was given a bigger number and a larger bredth of numbers?  [What I need]  I need a way of finding the value instantaneously by only doing the math, I tried using logarithms, but my answer was wrong, my knowledge of logs is a bit rusty and I need a little help.  Think of it as a student trying to solve a question on an SAT or having a timer for a test.
680
First off, here is some code:  int main()  {     int days[] = {1,2,3,4,5};     int *ptr = days;     printf("%u\n", sizeof(days));     printf("%u\n", sizeof(ptr));      return 0; }   Is there a way to find out the size of the array that ptr is pointing to (instead of just giving its size, which is four bytes on a 32-bit system)?
33272
There is this example code, but then it starts talking about millisecond / nanosecond problems.  The same question is on MSDN, .  This is what I've got so far:  public Double CreatedEpoch {   get   {     DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();     TimeSpan span = (this.Created.ToLocalTime() - epoch);     return span.TotalSeconds;   }   set   {     DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();     this.Created = epoch.AddSeconds(value);   } }
87194
I've been told that code such as:  for (int i = 0; i &lt; x.length(); i++) {     // blah }   is actually O(n^2) because of the repeated calls to x.length(). Instead I should use:  int l = x.length(); for (int i = 0; i &lt; l; i++) {     // blah }   Is this true? Is string length stored as a private integer attribute of the String class? Or does String.length() really walk the whole string just to determine its length?
2899
I need a 'good' way to initialize the pseudo-random number generator in C++. I've found  that states:     In order to generate random-like   numbers, srand is usually initialized   to some distinctive value, like those   related with the execution time. For   example, the value returned by the   function time (declared in header   ctime) is different each second, which   is distinctive enough for most   randoming needs.   Unixtime isn't distinctive enough for my application. What's a better way to initialize this? Bonus points if it's portable, but the code will primarily be running on Linux hosts.  I was thinking of doing some pid/unixtime math to get an int, or possibly reading data from /dev/urandom.  Thanks!  EDIT  Yes, I am actually starting my application multiple times a second and I've run into collisions.
3011
Ok I hope I am mising something here as I really don't want this to be a bug.   The following piece of code returns 2. Per my understanding of the ceiling functionality, the result should be 3 because 7/3 is roughly 2.33333 and the ceiling should return 3.   Is this a bug or am I missing something? Thanks.   Integer pageNumber = (Integer) Math.ceil(7/3);   This returns 2 and not 3 as expected.   It works fine on other input. For example:  Integer pageNumber = (Integer) Math.ceil(8/5);   This returns 2 as expected.
2987
When I used to write libraries in C/C++ I got into the habit of having a method to return the compile date/time. This was always a compiled into the library so would differentiate builds of the library. I got this by returning a #define in the code:  C++:  #ifdef _BuildDateTime_    char* SomeClass::getBuildDateTime() {       return _BuildDateTime_;    } #else    char* SomeClass::getBuildDateTime() {       return "Undefined";    } #endif   Then on the compile I had a '-D_BuildDateTime_=Date' in the build script.  Is there any way to achieve this or similar in Java without needing to remember to edit any files manually or distributing any seperate files.  One suggestion I got from a co-worker was to get the ant file to create a file on the classpath and to package that into the JAR and have it read by the method.   Something like (assuming the file created was called 'DateTime.dat'):  // I know Exceptions and proper open/closing  // of the file are not done. This is just  // to explain the point! String getBuildDateTime() {     return new BufferedReader(getClass()             .getResourceAsStream("DateTime.dat")).readLine(); }   To my mind that's a hack and could be circumvented/broken by someone having a similarly named file outside the JAR, but on the classpath.  Anyway, my question is whether there is any way to inject a constant into a class at compile time  EDIT  The reason I consider using an externally generated file in the JAR a hack is because this is) a library and will be embedded in client apps. These client apps may define their own classloaders meaning I can't rely on the standard JVM class loading rules.  My personal preference would be to go with using the date from the JAR file as suggested by serg10.