java – Why is multithreading not giving me the speed-up I expected?

I recently decided to learn how to multithread Java programs, so I made a small program to compare the performance of serial and multithreaded programs that perform the same task.

I created a serial program that calculates the number of primes from 1 to 10 million, and timed it 50 times using a test program. Here’s the code for the serial program:

import java.util.Locale;
import java.text.NumberFormat;
/**
 * A serial program that calculates the number of primes less than a
 * certain number (which is hard coded). Used as a basis for
 * benchmarking the multi-threaded programs that do the same thing.
 *
 * @author Tirthankar Mazumder
 * @version 1.2
 * @date 2nd May, 2021
 */
public class PrimalityTestSerial {
    public static final long max = 10_000_000;
    public static void main(String() args) {
        final long startTime = System.currentTimeMillis();
        
        long num_primes = primeCalculator();
        
        final long endTime = System.currentTimeMillis();
        
        NumberFormat nf = NumberFormat.getInstance(Locale.US);
         
        System.out.println("Number of primes less than " + nf.format(max) + ": " + num_primes);
        System.out.println("Took " + (endTime - startTime) + " ms.");
        System.out.println();
    }
    
    private static boolean isPrime(long l) {
        long upper_bound = (long) Math.floor(Math.sqrt(l));
        
        for (long i = 2; i <= upper_bound; i++) {
            if (l % i == 0)
                return false;
        }
        
        return true;
    }
    
    public static long primeCalculator() {
        long num_primes = 0;
        
        for (long i = 2; i <= max; i++) {
            if (isPrime(i))
                num_primes++;
        }
        return num_primes;
    }
}

Here’s the code for the worker class used in the multithreaded version:

/**
 * A worker class for calculating the number of primes from start to end,
 * which are private member variables. Instances of this class are used
 * in the multithreaded version of PrimalityTestSerial.
 *
 * @author Tirthankar Mazumder
 * @version 1.2
 * @date 3rd May, 2021
 */
public class PrimalityTestWorker1 implements Runnable {
    //Member variables
    public static long totalPrimeCount = 0;
    private final long start;
    private final long end;
    
    public PrimalityTestWorker1(long start, long end) {
        this.start = start;
        this.end = end;
    }
    
    private synchronized void increment(long num) {
        totalPrimeCount += num;
    }
    
    private static boolean isPrime(long l) {
        long upper_bound = (long) Math.floor(Math.sqrt(l));
        
        for (long i = 2; i <= upper_bound; i++) {
            if (l % i == 0)
                return false;
        }
        
        return true;
    }
    
    private void numPrimes() {
        long primeCount = 0;
        for (long i = start; i <= end; i++) {
            if (isPrime(i))
                primeCount++;
        }
        increment(primeCount);
    }
    
    public void run() {
        numPrimes();
        Thread.yield();
    }
}

Here’s the main program which uses instances of PrimalityTest1Worker as threads:

import java.util.Locale;
import java.text.NumberFormat;
/**
 * The master program for the multithreaded primality test that creates
 * objects of the PrimalityTestWorker1 to make threads, and then collates
 * the results and prints them to stdout.
 *
 * @author Tirthankar Mazumder
 * @version 1.0=2
 * @date 3rd May, 2021
 */
public class PrimalityTestParallel1Runner {
    public static final int cores = Runtime.getRuntime().availableProcessors();
    //We will spawn as many threads as there are cores on the system, and not
    //more than that because we are not I/O bound here.

    public static final long max = PrimalityTestSerial.max;
    //For consistency.

    public static void main(String() args) {
        long startTime = System.currentTimeMillis();

        primeCalculator();

        long endTime = System.currentTimeMillis();
        
        NumberFormat nf = NumberFormat.getInstance(Locale.US);
        
        System.out.println("Number of primes less than " + nf.format(max) + ": " +
            PrimalityTestWorker1.totalPrimeCount);
            
        System.out.println("Took " + (endTime - startTime) + " ms.");
        System.out.println();
    }
    
    public static void primeCalculator() {
        Thread arrThreads() = new Thread(cores);

        long chunk = max / cores;
        long threadStart = 2;
        long threadEnd = threadStart + chunk;

        for (int i = 0; i < cores; i++) {
            Thread t = new Thread(new PrimalityTestWorker1(threadStart, threadEnd));
            t.start();
            arrThreads(i) = t;

            threadStart = threadEnd + 1;
            threadEnd = (threadEnd + chunk > max) ? max : threadEnd + chunk;
        }

        for (int i = 0; i < cores; i++) {
            try {
                arrThreads(i).join(); 
            } catch (InterruptedException e) {
                System.out.println("Was interrupted.");
                return;
            }
        }
    }
}

Finally, here’s the code for the testing program, which runs each program 50 times and then calculates the average runtimes:

import java.util.Arrays;
/**
 * A wrapper class that handles benchmarking the performances of
 * PrimalityTestSerial and PrimalityTestParallel1Runner and then
 * prints information about the results to stdout.
 *
 * @author Tirthankar Mazumder
 * @version 1.0
 * @date 8th May, 2021
 */
public class PrimalityTestSuite {
    public static final int n = 50;
    //Number of test runs to perform
    
    public static void main(String() args) {
        long totalSerialTime = 0;
        long totalParallelTime = 0;
        
        long serialTimes() = new long(n);
        
        double avgSerialTime = 0;
        double avgParallelTime = 0;
        
        System.out.println("Starting Serial runs...");
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            PrimalityTestSerial.primeCalculator();
            serialTimes(i) = System.currentTimeMillis();
        }
        
        for (int i = 0; i < n; i++) {
            serialTimes(i) -= startTime;
            for (int j = 0; j < i; j++) {
                serialTimes(i) -= serialTimes(j);
                //to get rid of the time taken by the previous runs
            }
            avgSerialTime += serialTimes(i);
        }
        
        avgSerialTime /= n;
        
        long parallelTimes() = new long(n);
        
        System.out.println("Starting parallel runs...");
        startTime = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            PrimalityTestParallel1Runner.primeCalculator();
            parallelTimes(i) = System.currentTimeMillis();
        }
        
        for (int i = 0; i < n; i++) {
            parallelTimes(i) -= startTime;
            for (int j = 0; j < i; j++) {
                parallelTimes(i) -= parallelTimes(j);
                //to get rid of the time taken by the previous runs
            }
            avgParallelTime += parallelTimes(i);
        }
        
        avgParallelTime /= n;
        
        Arrays.sort(serialTimes);
        Arrays.sort(parallelTimes);
        
        double bestThreeSerialAvg = (serialTimes(0) + serialTimes(1)
                                     + serialTimes(2)) / 3;
        double bestThreeParallelAvg = (parallelTimes(0) + parallelTimes(1)
                                     + parallelTimes(2)) / 3;
        
        System.out.println();
        System.out.println("Results:");
        
        System.out.println("Average of " + n + " Serial Runs: " + avgSerialTime + " ms.");
        System.out.println("Average of " + n + " Parallel Runs: " + avgParallelTime + " ms.");
        
        System.out.println();
        System.out.println("Average speed-up: " + avgSerialTime / avgParallelTime + "x");
        System.out.println();
        
        System.out.println("Average of best 3 Serial Runs: " + bestThreeSerialAvg + " ms.");
        System.out.println("Average of best 3 Parallel Runs: " + bestThreeParallelAvg + " ms.");
        
        System.out.println();
        System.out.println("Average speed-up (w.r.t. best run times): "
                            + bestThreeSerialAvg / bestThreeParallelAvg + "x");
        System.out.println();
    }
}

Here are the results from the test program:

Starting Serial runs...
Starting parallel runs...

Results:
Average of 50 Serial Runs: 4378.92 ms.
Average of 50 Parallel Runs: 1529.2 ms.

Average speed-up: 2.8635364896678x

Average of best 3 Serial Runs: 4328.0 ms.
Average of best 3 Parallel Runs: 1297.0 ms.

Average speed-up (w.r.t. best run times): 3.3369313801079414x

From here, it is obvious that the average speed-up is simply around 3x. However, this is surprising because I expect the multi-threaded program to run 7 to 8 times faster (because the serial program uses just 1 core, whereas the multi-threaded program should use all 8 cores on my system.)

So my question is, why is the multi-threaded program not as fast as I expect it to be?

c++ – Algorithm for finding a fractional palindrome not working as expected

Guidelines: I am not allowed to use any external library classes except for “cin” and “cout”. I must follow the odd syntactic conventions, such as naming and programmer classes. Finally, it must be able to run on older IDEs for whatever reason, similar to first rule of not using any new/advanced code, and keeping it very primitive.

My issue: Code works for simpler fractions but I am getting strange outputs for my attempt at the palindrome common digit identifier “displayCommonPalindromeDigitWG”. Example: I put in 444/44544 and the output will be “9 common digits of 4” (note: it is finding total digits instead of common digits in said example). An additional note is that this is old code of mines and I have been asked to fix that issue and refactor, and as a novice to C++ I am a bit lost.

I will paste the odd cpp file below, if more context is needed I will gladly edit this post. Thank you!

    #include <iostream>
    #include "fractionUtility.h"
    #include "FractionWG.h"
    using namespace std;

    bool fractionUtility::isPalindromeWG(FractionWG* fwg) {
        return fractionUtility::isPalindromeWG(fwg->getNum())
            && fractionUtility::isPalindromeWG(fwg->getDenom());
    }

    void fractionUtility::displayCommonPalindromeDigitWG(FractionWG* fwg) {
    int commonWG = 0;
    int dWG = (fwg->getDenom() > 0) ? fwg->getDenom() : -(fwg->getDenom());
    int nWG = (fwg->getNum() > 0) ? fwg->getNum() : -(fwg->getNum());

    while (nWG > 0) {
        while (dWG > 0) {
            if (dWG % 10 == nWG % 10) {
                commonWG++;
            }
            dWG /= 10;
        }
        nWG /= 10;
        dWG = (fwg->getDenom() > 0) ? fwg->getDenom() : -(fwg->getDenom());
    }
    nWG = (fwg->getNum() > 0) ? fwg->getNum() : -(fwg->getNum());

    std::cout << "n    There is/are " << commonWG << " common digit(s) of" << std::endl;
    while (nWG > 0) {
        while (dWG > 0) {
            if (nWG % 10 == dWG % 10) {
                std::cout << "      " << nWG % 10 << "n";
            }
            dWG /= 10;
        }
        nWG /= 10;
        dWG = fwg->getDenom();
    }
}

bool fractionUtility::isPalindromeWG(int x) {
    x = (x > 0) ? x : -x;
    int reverseWG = 0;
    int tempWG = x;

    while (tempWG > 0) {
        reverseWG *= 10;
        reverseWG += tempWG % 10;
        tempWG /= 10;
    }

    return x == reverseWG;
}

int fractionUtility::powerWG(int b, int e) {
    int productWG = 1;

    for (int i = 1; i <= e; i++) {
        productWG *= b;
    }
    return productWG;
}

python – iterated each cell in a dataframe using for loop and transformed the data. Why is my dataframe not updated with the expected data

Few cells of my dataframe have duplicates merged with a special character ||||.
example: 20210319||||20210319, 63||||64.17, 14.26||||14.26

I am trying to check if a duplicate value is appended after the special character. if its a duplicate, i want to remove the duplicate value. if they are unique(eg : 63||||64.17), i want to keep it. I tried the belw code, but i am not able to get the expected dataframe.

Code:

    for rowIndex, row in df1.iterrows():
        for columnIndex, value in row.items():
            f, s = value(:len(value)//2), value(len(value)//2:)
            f = f.replace('|','')
            s = s.replace('|','')
            if f == s:
                value = f
                print(value)
                #a.append(value)
            else:
                value = f+"||||"+s
                print(value)
                #a.append(value)

magento2 – Expected to start loader but did not find one in the dom : loader.js:210 in magento 2 product page

i have see issue in my browser console : Expected to start loader but did not find one in the dom : loader.js:210 in product page.

 if (window.console && !ctx.parents('(data-role="loader")').length) {
                    console.warn('Expected to start loader but did not find one in the dom');
                }

When product page loading Or click on swatch option in configure product.
In product page loader perfectly show and hide but I cant debug why its showing me Expected to start loader but did not find one in the dom.

Applying replacement rules to products doesn’t work as expected

I have the following issue: I’d like to apply some replacement rules, for example

rules:={f(x)/t :> ff(x), g(x)/t :> gg(x)}

to an expression, e.g. like this:

(f(x)*g(x)/(t^2))/. rules

Surprisingly, this doesn’t give the expected result

ff(x)*gg(x)

How do I fix this? Sorry if it’s an easy question, I’m still a beginner with Mathematica.

SHA256 Hash in Ruby not expected value

If I use OpenSSL to SHA256 hash the string hashthisstring123$

> echo -n "hashthisstring123$" | openssl dgst -sha256

I get this result:

> 052582d953f79d1e8502fdf063850888ee8426d3a5a6f46c1a0394d16056a51b

I have code to do this in Ruby, like this:

def self.test1
    str = "hashthisstring123$"
    retval = Digest::SHA256.hexdigest(str)
    return retval
end

It gives this (expected) result:

> Util.test1
=> "052582d953f79d1e8502fdf063850888ee8426d3a5a6f46c1a0394d16056a51b"

If I use OpenSSL to SHA256 hash the string 6nQ5t$hWGu8Kpassword123

> echo -n "6nQ5t$hWGu8Kpassword123" | openssl dgst -sha256

I get this result:

> 57cd553e7886a2c8eea92926e420d33d315418ffe6b98e5c34f1679607207d75

In Ruby, I have a method like this:

def self.test2
    str = "6nQ5t$hWGu8Kpassword123"
    retval = Digest::SHA256.hexdigest(str)
    return retval
end

And it gives this (unexpected) result:

> Util.test2
=> "1924de3da90f631c0943a47e4d4d80362d622e9656b5e2861f252a16bffb3d88"

What’s going on here?

ctrl + ` shortcut doesn’t work as expected in VS Code

I found about the shortcut ctrl + ` to toggle between editor and terminal in vs code. The shortcut was working flawlessly, I could toggle between the two easily. But then I tried to change the shortcut(in which I failed) but it seems like I have changed some setting.

Now when I use the shortcut when the focus is terminal, it goes to editor(this part is fine) but then the terminal window hides down. I want it to remain there so I can read where my errors are coming from.

I have tried resetting everything to default settings from the keyboard shortcut but it is of no use

Go expected identifier on left side of :=syntax

Hello I am trying to make a connection to postgres using go, but I have the following error:

on this line :

conn.pool, err := sql.Open(“postgres”, uri)

err:

expected identifier on left side of :=syntax

I’m new to go and I don’t know why and how to resolve this error, if someone can help me where I’m going wrong.

package database

import (
    "database/sql"
    "fmt"
    "log"
    "os"
    "strconv"
)

type Db struct {
    pool *sql.DB
}

type Connection interface {
    Close()
    DB() *sql.DB
}

func NewPostgreSQLsql() (Connection, error) {
    var conn Db
    
    uri := getURI()

    conn.pool, err := sql.Open("postgres", uri)

    if err != nil {
        log.Fatal(err.Error())
        return nil, err
    }

    if err := conn.Ping(); err != nil {
        log.Fatal(err.Error())
        return nil, err
    }

    return &conn, nil
}

func (c *db) DB() *sql.DB {
    return c.pool
}

func (c *Db) Close() {
    c.pool.Close()
}

func getURI() string {
    dbPort, err := strconv.Atoi(os.Getenv("DB_PORT"))
    if err != nil {
        log.Println("error on load db port from env:", err.Error())
        dbPort = 5432
    }
    return fmt.Sprintf(os.Getenv("DB_HOST"),
        dbPort,
        os.Getenv("DB_USER"),
        os.Getenv("DB_NAME"),
        os.Getenv("DB_PASSWORD"))
}

applescript – My Apple Script Editor code doesn’t work gives “Syntax Error Expected end of line but found identifier.”

The problem is the version of Evernote I tried is not AppleScript scriptable.

When trying to add Evernote to the Library in Script Editor, in order to review its AppleScript dictionary, it errs with: Add Item Unable to add the item because it is not scriptable.

Additionally, when running the following command in Script Editor:

tell application "System Events" to ¬
    get has scripting terminology of application process "Evernote"

Its result is: false


Apparently at one time Evernote was AppleScript scriptable, however, in macOS Catalina, testing with Evernote from https://evernote.com/download/ and checking Evernote > About Evernote it shows:

10.11.5-mac-ddl-public (2530)
Editor: v121.2.15734
Service: v1.32.4
© 2019 – 2021 Evernote Corporation. All rights reserved

Looking for the typical AppleScript dictionary in /Applications/Evernote.app/Contents/Resources/ there is no Evernote.sdef files as would be expected if it was fully AppleScript scriptable.


If you do have a version of Evernote that is AppleScript scriptable then try the following, which I cannot test under the circumstances:

Change note1 to note in:

set myNote to create note1 with text myTitle title myTitle notebook "Imported Notes" tags ("imported_from_notes")

You might also want to put in some parentheses. e.g.

set myNote to (create note with text myTitle title myTitle notebook "Imported Notes" tags ("imported_from_notes"))

Unfortunately without a version of Evernote that is AppleScript scriptable, I cannot offer more.

anydice – How can I calculate expected Stunt Points per attack when FIRST dropping a d6?

Here’s an example anydice function which calculates this kind of result:

function: stunt DICE:s STUNT:n DC:n {
  if 1@DICE + 2@DICE + STUNT < DC {
    result: 0
  }
  loop X over {1..#DICE-1}{
    if (X@DICE = (X+1)@DICE | X@DICE = STUNT | (X+1)@DICE = STUNT) & X@DICE + (X+1)@DICE + STUNT >= DC { result: STUNT }
  }
  result: 0
}

Let’s walk through it.

We invoke the function by calling (stunt Xd6 1d6 DC), where Xd6 is our dice pool, the other 1d6 is our stunt die, and DC is the target we need to roll on the dice. When the function runs, the rolled dice pool will be cast to a sequence, which anydice will helpfully automatically sort from highest to lowest.

The first if statement in the function checks to see whether the roll can possibly succeed – we take the two highest dice from the dice pool and the stunt die and see if they are less than the target number. If so, we immediately return 0 as it not possible to succeed on the roll.

Then we start iterating over the pool using a loop in order to check for any doubles, starting with the first two dice. If any two of the two dice under consideration and the stunt die are equal to each other, and the total of those two dice and the stunt die is enough to beat the target DC, the test has succeeded with stunt points – we return the value of the stunt die.

We know that any two dice in the sequence must be adjacent to each other in order to have a chance of being doubles, because the sequence has been sorted already, so don’t need to exhaustively check every possible combination from the sequence – stepping along it in adjacent pairs, using X@DICE and (X+1)@DICE, is good enough.

Otherwise, if we get all the way through the dice pool without finding any doubles that also beat the target DC, we return 0 to indicate the test has succeeded with no stunt points.

Here’s a screencap of some sample output from the function:

Tables of anydice output for pools from 2d6 to 5d6

Interesting modifications to make to the function might be to return -1 instead of 0 if the test fails, which will show you a distribution which indicates both the likelihood of a specific number of stunt points and the likelihood of passing at all (though it will skew the averages), or to return d{} (the “empty die”) to produce a distribution ignoring rolls that fail (i.e. how many stunt points are we likely to get if we succeed?).