Selenium speed Ruby Vs Java - java

This isn't meant as a war between which is faster Java or Ruby but I've always been lead to believe that Selenium would run faster in Java compared to Ruby
Example
Example
I've just knocked up a quick and dirty test that opens youtube does a search and loops 10 times.
Ruby out performs Java every time I run this.
I'm not using Eclipse or Rubymine just using command line.
Ruby version:
require 'selenium-webdriver'
test_start = Time.now
for i in 1..10
beginning_time = Time.now
driver = Selenium::WebDriver.for :chrome, driver_path:"C:\\ChromeDriver\\chromedriver.exe"
driver.navigate.to "https://www.youtube.com/"
element = driver.find_element(:id, 'masthead-search-term')
element.send_keys "Selenium"
element.submit
puts(driver.title)
driver.quit
end_time = Time.now
puts "Attempt #{i} Seconds: #{(end_time - beginning_time)}"
end
test_end = Time.now
puts "After 10 attempts the total Seconds: #{(test_end - test_start)}"
Java version:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class SpeedTest {
public static void main(String[] args) {
long testStart = System.currentTimeMillis();
for(int x = 0; x < 10; x++){
long startTime = System.currentTimeMillis();
System.setProperty("webdriver.chrome.driver", "C:\\ChromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.youtube.com/");
WebElement element = driver.findElement(By.id("masthead-search-term"));
element.sendKeys("Selenium");
element.submit();
System.out.println(driver.getTitle());
driver.quit();
long endTime = System.currentTimeMillis();
System.out.println("Attempt " + x + " seconds:");
System.out.printf("%.6f%n ", (endTime - startTime)/1e3);
}
long testEnd = System.currentTimeMillis();
System.out.printf("Total seconds for 10 attempts: %.6f%n ", (testEnd - testStart)/1e3);
}
}
Have I made a stupid mistake or is Ruby faster for this sort of testing?

Related

.toNanos() method does not work correctly

I tried to make a method that will give me an idea of how much time it takes to my programs to run, and for an unknown reason, I can not get the nanoseconds.
I tried to read about the below classes but could not find out what I am doing wrong:
import java.time.Duration;
import java.time.Instant;
The methods:
public static String calcExecutionTime(Instant startTime, Instant endTime) {
if ((Duration.between(startTime, endTime).toNanos()) < 1000000) {
return Duration.between(startTime, endTime).toNanos() + " nanoseconds.";
} else if ((Duration.between(startTime, endTime).toMillis()) < 1000) {
return Duration.between(startTime, endTime).toMillis() + " milliseconds.";
} else if ((Duration.between(startTime, endTime).toSeconds()) < 100) {
return Duration.between(startTime, endTime).toSeconds() + " seconds.";
} else if ((Duration.between(startTime, endTime).toMinutes()) < 60) {
return Duration.between(startTime, endTime).toMinutes() + " minutes.";
} else {
return Duration.between(startTime, endTime).toHours() + " hoursm.";
}
}
Main here:
Instant instantStart = Instant.now();
Instant instantEnd = Instant.now();
System.out.print("Execution time for this program: " + calcExecutionTime(instantStart, instantEnd));
If I use the old System.nanoTime(); I get a result of 300-400 nanoseconds but with toNanos() I get 0 in this same situation.
Edit:
I do not use getNano() I use toNanos()
I would go with #Pshemo's comment about Instant.now().
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#now-- :
This will query the system UTC clock to obtain the current instant.
Where the link leads to:
This may use System.currentTimeMillis(), or a higher resolution clock if one is available.
So it may or may not have a higher precision than milliseconds. In your case the "may not have" seems to apply.

How can I get seconds and milliseconds together from time?

I am trying to get page load time in automation testing project.
pageLoad3.start();
WebDriverWait wait3 = new WebDriverWait(driver, 30);
wait3.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(hotelNameDetailsXpath)));
pageLoad3.stop();
long pageLoadTime_ms5 = pageLoad3.getTime();
long pageLoadTime_Seconds5 = pageLoadTime_ms5 / 1000;
//System.out.println("Time taken to get load Total price element ::");
System.out.println("pageLoadTime_ms5 ::"+pageLoadTime_ms5);
System.out.println("Time taken to load DB Response :: " + pageLoadTime_Seconds5 + " seconds");
Output:
pageLoadTime_ms5 ::11479
Time taken to load DB Response :: 11 seconds
I am getting 11 seconds but not able to get for 479, how can I get it in below format?
Actual Requirement: I want time to get in below format like
11 seconds 47 milliseconds i.e. (00:11:47)
To get the output as 11 seconds 47 milliseconds you can use the following solution:
Code Block:
public class division_by_1000 {
public static void main(String[] args) {
//long pageLoadTime_ms5 = pageLoad3.getTime();
// assuming pageLoadTime_ms5 = 11479
String pageLoadTime_ms5 = "11479";
System.out.println("pageLoadTime_ms5 ::"+pageLoadTime_ms5);
System.out.println("Time taken to load DB Response :: " + (Integer.parseInt(pageLoadTime_ms5)/1000) + " seconds " + (Integer.parseInt(pageLoadTime_ms5)%1000) + " millisseconds ");
}
}
Console Output:
pageLoadTime_ms5 ::11479
Time taken to load DB Response :: 11 seconds 479 millisseconds

Weka output predictions

I've used the Weka GUI for training and testing a file (making predictions), but can't do the same with the API. The error I'm getting says there's a different number of attributes in the train and test files. In the GUI, this can be solved by checking "Output predictions".
How to do something similar using the API? do you know of any samples out there?
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.meta.FilteredClassifier;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.NominalToBinary;
import weka.filters.unsupervised.attribute.Remove;
public class WekaTutorial
{
public static void main(String[] args) throws Exception
{
DataSource trainSource = new DataSource("/tmp/classes - edited.arff"); // training
Instances trainData = trainSource.getDataSet();
DataSource testSource = new DataSource("/tmp/classes_testing.arff");
Instances testData = testSource.getDataSet();
if (trainData.classIndex() == -1)
{
trainData.setClassIndex(trainData.numAttributes() - 1);
}
if (testData.classIndex() == -1)
{
testData.setClassIndex(testData.numAttributes() - 1);
}
String[] options = weka.core.Utils.splitOptions("weka.filters.unsupervised.attribute.StringToWordVector -R first-last -W 1000 -prune-rate -1.0 -N 0 -stemmer weka.core.stemmers.NullStemmer -M 1 "
+ "-tokenizer \"weka.core.tokenizers.WordTokenizer -delimiters \" \\r\\n\\t.,;:\\\'\\\"()?!\"");
Remove remove = new Remove();
remove.setOptions(options);
remove.setInputFormat(trainData);
NominalToBinary filter = new NominalToBinary();
NaiveBayes nb = new NaiveBayes();
FilteredClassifier fc = new FilteredClassifier();
fc.setFilter(filter);
fc.setClassifier(nb);
// train and make predictions
fc.buildClassifier(trainData);
for (int i = 0; i < testData.numInstances(); i++)
{
double pred = fc.classifyInstance(testData.instance(i));
System.out.print("ID: " + testData.instance(i).value(0));
System.out.print(", actual: " + testData.classAttribute().value((int) testData.instance(i).classValue()));
System.out.println(", predicted: " + testData.classAttribute().value((int) pred));
}
}
}
Error:
Exception in thread "main" java.lang.IllegalArgumentException: Src and Dest differ in # of attributes: 2 != 17152
This was not an issue for the GUI.
You need to ensure that categories in train and test sets are compatible, try to
combine train and test sets
List item
preprocess them
save them as arff
open two empty files
copy the header from the top to line "#data"
copy in training set into first file and test set into second file

Processing CQEngine ResultSet with Scala foreach is very slow

I'm trying to process CQEngine's ResultSet using Scala's foreach, but the result is very slow.
Following is the snippet of what I'm trying to do
import collection.JavaConversions._
val query = existIn(myOtherCollection, REFERENCE, REFERENCE)
val resultSet = myIndexCollection.retrieve(query)
resultSet.foreach(r =>{
//do something here
})
Somehow the .foreach method is very slow. I tried to debug by putting SimonMonitor and change the .foreach using while(resultSet.hasNext), surprisingly, every call to hasNext method takes about 1-2 seconds. That's very slow.
I tried to create the same version using Java, and the Java version is super fast.
Please help
I am not able to reproduce your problem with the below test code. Can you try it on your system and let me know how it runs?
(Uncomment line 38, garages.addIndex(HashIndex.onAttribute(Garage.BRANDS_SERVICED)), to make BOTH the Scala and Java iterators run blazingly fast...)
The output first (time in milliseconds):
Done adding data
Done adding index
============== Scala ==============
Car{carId=4, name='BMW M3', description='2013 model', features=[radio, convertible]}
Time : 3 seconds
Car{carId=1, name='Ford Focus', description='great condition, low mileage', features=[spare tyre, sunroof]}
Time : 1 seconds
Car{carId=2, name='Ford Taurus', description='dirty and unreliable, flat tyre', features=[spare tyre, radio]}
Time : 2 seconds
============== Java ==============
Car{carId=4, name='BMW M3', description='2013 model', features=[radio, convertible]}
Time : 3 seconds
Car{carId=1, name='Ford Focus', description='great condition, low mileage', features=[spare tyre, sunroof]}
Time : 1 seconds
Car{carId=2, name='Ford Taurus', description='dirty and unreliable, flat tyre', features=[spare tyre, radio]}
Time : 2 seconds
Code below:
import collection.JavaConversions._
import com.googlecode.cqengine.query.QueryFactory._
import com.googlecode.cqengine.CQEngine;
import com.googlecode.cqengine.index.hash._;
import com.googlecode.cqengine.IndexedCollection;
import com.googlecode.cqengine.query.Query;
import java.util.Arrays.asList;
object CQTest {
def main(args: Array[String]) {
val cars: IndexedCollection[Car] = CQEngine.newInstance();
cars.add(new Car(1, "Ford Focus", "great condition, low mileage", asList("spare tyre", "sunroof")));
cars.add(new Car(2, "Ford Taurus", "dirty and unreliable, flat tyre", asList("spare tyre", "radio")));
cars.add(new Car(3, "Honda Civic", "has a flat tyre and high mileage", asList("radio")));
cars.add(new Car(4, "BMW M3", "2013 model", asList("radio", "convertible")));
// add cruft to try and slow down CQE
for (i <- 1 to 10000) {
cars.add(new Car(i, "BMW2014_" + i, "2014 model", asList("radio", "convertible")))
}
// Create an indexed collection of garages...
val garages: IndexedCollection[Garage] = CQEngine.newInstance();
garages.add(new Garage(1, "Joe's garage", "London", asList("Ford Focus", "Honda Civic")));
garages.add(new Garage(2, "Jane's garage", "Dublin", asList("BMW M3")));
garages.add(new Garage(3, "John's garage", "Dublin", asList("Ford Focus", "Ford Taurus")));
garages.add(new Garage(4, "Jill's garage", "Dublin", asList("Ford Focus")));
// add cruft to try and slow down CQE
for (i <- 1 to 10000) {
garages.add(new Garage(i, "Jill's garage", "Dublin", asList("DONT_MATCH_CARS_BMW2014_" + i)))
}
println("Done adding data")
// cars.addIndex(HashIndex.onAttribute(Car.NAME));
// garages.addIndex(HashIndex.onAttribute(Garage.BRANDS_SERVICED));
println("Done adding index")
val query = existsIn(garages, Car.NAME, Garage.BRANDS_SERVICED, equal(Garage.LOCATION, "Dublin"))
val resultSet = cars.retrieve(query)
var previous = System.currentTimeMillis()
println("============== Scala ============== ")
// Scala version
resultSet.foreach(r => {
println(r);
val t = (System.currentTimeMillis() - previous)
System.out.println("Time : " + t / 1000 + " seconds")
previous = System.currentTimeMillis()
})
println("============== Java ============== ")
previous = System.currentTimeMillis()
// Java version
val i: java.util.Iterator[Car] = resultSet.iterator()
while (i.hasNext) {
val r = i.next()
println(r);
val t = (System.currentTimeMillis() - previous)
System.out.println("Time : " + t / 1000 + " seconds")
previous = System.currentTimeMillis()
}
}
}

Java: SimpleDateFormat timestamp not updating

Evening,
I'm trying to create a timestamp for when an entity is added to my PriorityQueue using the following SimpleDate format: [yyyy/MM/dd - hh:mm:ss a] (Samples of results below)
Nano-second precision NOT 100% necessary
1: 2012/03/09 - 09:58:36 PM
Do you know how I can maintain an 'elapsed time' timestamp that shows when customers have been added to the PriorityQueue?
In the StackOverflow threads I've come across, most say to use System.nanoTime(); although I can't find resources online to implement this into a SimpleDateFormat. I have also consulted with colleagues.
Also, I apologize for not using syntax highlighting (if S.O supports it)
Code excerpt [unused methods omitted]:
<!-- language: java -->
package grocerystoresimulation;
/*****************************************************************************
* #import
*/
import java.util.PriorityQueue;
import java.util.Random;
import java.util.ArrayList;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/************************************************************************************
public class GroceryStoreSimulation {
/************************************************************************************
* #fields
*/
private PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
private Random rand = new Random(); //instantiate new Random object
private Date date = new Date();
private DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd - hh:mm:ss a");
private ArrayList<String> timeStamp = new ArrayList<String>(); //store timestamps
private int customersServed; //# of customers served during simulation
/************************************************************************************
* #constuctor
*/
public GroceryStoreSimulation(){
System.out.println("Instantiated new GroceryStoreSimulation # ["
+ dateFormat.format(date) + "]\n" + insertDivider());
//Program body
while(true){
try{
Thread.sleep(generateWaitTime());
newCustomer(customersServed);
} catch(InterruptedException e){/*Catch 'em all*/}
}
}
/************************************************************************************
* #param String ID
*/
private void newCustomer(int ID){
System.out.println("Customer # " + customersServed + " added to queue. . .");
pq.offer(ID); //insert element into PriorityQueue
customersServed++;
assignArrivalTime(ID); //call assignArrivalTime() method
} //newCustomer()
/************************************************************************************
* #param String ID
*/
private void assignArrivalTime(int ID){
timeStamp.add(ID + ": " + dateFormat.format(date));
System.out.println(timeStamp.get(customersServed-1));
} //assignArrivalTime()
/************************************************************************************
* #return int
*/
private int generateWaitTime(){
//Local variables
int Low = 1000; //1000ms
int High = 4000; //4000ms
int waitTime = rand.nextInt(High-Low) + Low;
System.out.println("Delaying for: " + waitTime);
return waitTime;
}
//***********************************************************************************
private static String insertDivider(){
return ("******************************************************************");
}
//***********************************************************************************
} //GroceryStoreSimulation
Problem:
Timestamp does not update, only represents initial runtime (see below)
Delaying by 1-4 seconds w/Thread.sleep(xxx) (pseudo-randomly generated)
Problem may be in the assignArrivalTime() method
Output:
run:
Instantiated new GroceryStoreSimulation # [2012/03/09 - 09:58:36 PM]
******************************************************************
Delaying for: 1697
Customer # 0 added to queue. . .
0: 2012/03/09 - 09:58:36 PM
Delaying for: 3550
Customer # 1 added to queue. . .
1: 2012/03/09 - 09:58:36 PM
Delaying for: 2009
Customer # 2 added to queue. . .
2: 2012/03/09 - 09:58:36 PM
Delaying for: 1925
BUILD STOPPED (total time: 8 seconds)
Thank you for your assistance, I hope my question is clear enough & I`ve followed your formatting guidelines sufficiently.
You have to use a new instance of Date everytime to get most recent timestamp.
private void assignArrivalTime(int ID){
timeStamp.add(ID + ": " + dateFormat.format(date));
------------------------------------------------^^^^
Try replacing date by new Date() in above line.

Categories

Resources