WeixiangYan/CodeTransOcean huggingface dataset:
Task: Bitmap_Flood fill




Go: package raster

func (b *Bitmap) Flood(x, y int, repl Pixel) {
    targ, _ := b.GetPx(x, y)
    var ff func(x, y int)
    ff = func(x, y int) {
        p, ok := b.GetPx(x, y)
        if ok && p.R == targ.R && p.G == targ.G && p.B == targ.B {
            b.SetPx(x, y, repl)
            ff(x-1, y)
            ff(x+1, y)
            ff(x, y-1)
            ff(x, y+1)
        }
    }
    ff(x, y)
}


Java: import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.Deque;
import java.util.LinkedList;

public class FloodFill {
  public void floodFill(BufferedImage image, Point node, Color targetColor, Color replacementColor) {
    int width = image.getWidth();
    int height = image.getHeight();
    int target = targetColor.getRGB();
    int replacement = replacementColor.getRGB();
    if (target != replacement) {
      Deque<Point> queue = new LinkedList<Point>();
      do {
        int x = node.x;
        int y = node.y;
        while (x > 0 && image.getRGB(x - 1, y) == target) {
          x--;
        }
        boolean spanUp = false;
        boolean spanDown = false;
        while (x < width && image.getRGB(x, y) == target) {
          image.setRGB(x, y, replacement);
          if (!spanUp && y > 0 && image.getRGB(x, y - 1) == target) {
            queue.add(new Point(x, y - 1));
            spanUp = true;
          } else if (spanUp && y > 0 && image.getRGB(x, y - 1) != target) {
            spanUp = false;
          }
          if (!spanDown && y < height - 1 && image.getRGB(x, y + 1) == target) {
            queue.add(new Point(x, y + 1));
            spanDown = true;
          } else if (spanDown && y < height - 1 && image.getRGB(x, y + 1) != target) {
            spanDown = false;
          }
          x++;
        }
      } while ((node = queue.pollFirst()) != null);
    }
  }
}
Task: Bitmap_Flood fill




Go: package raster

func (b *Bitmap) Flood(x, y int, repl Pixel) {
    targ, _ := b.GetPx(x, y)
    var ff func(x, y int)
    ff = func(x, y int) {
        p, ok := b.GetPx(x, y)
        if ok && p.R == targ.R && p.G == targ.G && p.B == targ.B {
            b.SetPx(x, y, repl)
            ff(x-1, y)
            ff(x+1, y)
            ff(x, y-1)
            ff(x, y+1)
        }
    }
    ff(x, y)
}




Python: from collections import deque

image_file = "image.png"
fill_color = color(250, 0, 0)
tolerance = 15
allowed = False

def setup():
    global img
    size(600, 400)
    img = loadImage(image_file)
    fill(0, 0, 100)
    textSize(18)
    show()
    
def show():
    image(img, 0, 0, width, height)
    text("Tolerance = {}    (Use mouse wheel to change)".format(tolerance),
         100, height - 30)
    text("Right click to reset", 100, height - 10)
 
def draw():
    global allowed
    if allowed:
        show()
        allowed = False

def mousePressed():
    global allowed, img
    if mouseButton == RIGHT:
        img = loadImage(image_file)
    else:
        img.loadPixels()
        flood(mouseX, mouseY)
        img.updatePixels()
    allowed = True    

def mouseWheel(event):
    global allowed, tolerance
    e = event.getCount()
    tolerance += 2 * e
    if tolerance > 128:
        tolerance = 128
    if tolerance < 0:
        tolerance = 0
    allowed = True

def flood(x, y):
    target_color = img.pixels[pixel_position(mouseX, mouseY)]
    if target_color != fill_color:
        queue = deque()
        queue.append((x, y))
        while len(queue) > 0:
            p_x, p_y = queue.popleft()
            if (check(p_x, p_y, target_color)):
                queue.append((p_x, p_y - 1))
                queue.append((p_x, p_y + 1))
                queue.append((p_x - 1, p_y))
                queue.append((p_x + 1, p_y))

def pixel_position(x, y):
    return x + (y * img.width)

def check(x, y, target_color):
    if x < 0 or y < 0 or y >= img.height or x >= img.width:
        return False
    pp = img.pixels[pixel_position(x, y)]
    test_tolerance = (abs(green(target_color) - green(pp)) < tolerance
                      and abs(red(target_color) - red(pp)) < tolerance
                      and abs(blue(target_color) - blue(pp)) < tolerance)
    if not test_tolerance:
        return False
    img.pixels[pixel_position(x, y)] = fill_color
    return True
Task: Bitmap_Flood fill


C++: #ifndef PROCESSING_FLOODFILLALGORITHM_H_
#define PROCESSING_FLOODFILLALGORITHM_H_

#include <opencv2/opencv.hpp>
#include <string.h>
#include <queue>

using namespace cv;
using namespace std;

class FloodFillAlgorithm {
public:
    FloodFillAlgorithm(Mat* image) :
        image(image) {
    }
    virtual ~FloodFillAlgorithm();

    void flood(Point startPoint, Scalar tgtColor, Scalar loDiff);
    void flood(Point startPoint, Mat* tgtMat);

protected:
    Mat* image;
private:
    bool insideImage(Point p);
};

#endif 




Java: import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.Deque;
import java.util.LinkedList;

public class FloodFill {
  public void floodFill(BufferedImage image, Point node, Color targetColor, Color replacementColor) {
    int width = image.getWidth();
    int height = image.getHeight();
    int target = targetColor.getRGB();
    int replacement = replacementColor.getRGB();
    if (target != replacement) {
      Deque<Point> queue = new LinkedList<Point>();
      do {
        int x = node.x;
        int y = node.y;
        while (x > 0 && image.getRGB(x - 1, y) == target) {
          x--;
        }
        boolean spanUp = false;
        boolean spanDown = false;
        while (x < width && image.getRGB(x, y) == target) {
          image.setRGB(x, y, replacement);
          if (!spanUp && y > 0 && image.getRGB(x, y - 1) == target) {
            queue.add(new Point(x, y - 1));
            spanUp = true;
          } else if (spanUp && y > 0 && image.getRGB(x, y - 1) != target) {
            spanUp = false;
          }
          if (!spanDown && y < height - 1 && image.getRGB(x, y + 1) == target) {
            queue.add(new Point(x, y + 1));
            spanDown = true;
          } else if (spanDown && y < height - 1 && image.getRGB(x, y + 1) != target) {
            spanDown = false;
          }
          x++;
        }
      } while ((node = queue.pollFirst()) != null);
    }
  }
}
Task: Bitmap_Flood fill


C++: #ifndef PROCESSING_FLOODFILLALGORITHM_H_
#define PROCESSING_FLOODFILLALGORITHM_H_

#include <opencv2/opencv.hpp>
#include <string.h>
#include <queue>

using namespace cv;
using namespace std;

class FloodFillAlgorithm {
public:
    FloodFillAlgorithm(Mat* image) :
        image(image) {
    }
    virtual ~FloodFillAlgorithm();

    void flood(Point startPoint, Scalar tgtColor, Scalar loDiff);
    void flood(Point startPoint, Mat* tgtMat);

protected:
    Mat* image;
private:
    bool insideImage(Point p);
};

#endif 






Python: from collections import deque

image_file = "image.png"
fill_color = color(250, 0, 0)
tolerance = 15
allowed = False

def setup():
    global img
    size(600, 400)
    img = loadImage(image_file)
    fill(0, 0, 100)
    textSize(18)
    show()
    
def show():
    image(img, 0, 0, width, height)
    text("Tolerance = {}    (Use mouse wheel to change)".format(tolerance),
         100, height - 30)
    text("Right click to reset", 100, height - 10)
 
def draw():
    global allowed
    if allowed:
        show()
        allowed = False

def mousePressed():
    global allowed, img
    if mouseButton == RIGHT:
        img = loadImage(image_file)
    else:
        img.loadPixels()
        flood(mouseX, mouseY)
        img.updatePixels()
    allowed = True    

def mouseWheel(event):
    global allowed, tolerance
    e = event.getCount()
    tolerance += 2 * e
    if tolerance > 128:
        tolerance = 128
    if tolerance < 0:
        tolerance = 0
    allowed = True

def flood(x, y):
    target_color = img.pixels[pixel_position(mouseX, mouseY)]
    if target_color != fill_color:
        queue = deque()
        queue.append((x, y))
        while len(queue) > 0:
            p_x, p_y = queue.popleft()
            if (check(p_x, p_y, target_color)):
                queue.append((p_x, p_y - 1))
                queue.append((p_x, p_y + 1))
                queue.append((p_x - 1, p_y))
                queue.append((p_x + 1, p_y))

def pixel_position(x, y):
    return x + (y * img.width)

def check(x, y, target_color):
    if x < 0 or y < 0 or y >= img.height or x >= img.width:
        return False
    pp = img.pixels[pixel_position(x, y)]
    test_tolerance = (abs(green(target_color) - green(pp)) < tolerance
                      and abs(red(target_color) - red(pp)) < tolerance
                      and abs(blue(target_color) - blue(pp)) < tolerance)
    if not test_tolerance:
        return False
    img.pixels[pixel_position(x, y)] = fill_color
    return True
Task: Intersecting number wheels



C#: using System;
using System.Collections.Generic;
using System.Linq;

public static class IntersectingNumberWheels
{
    public static void Main() {
        TurnWheels(('A', "123")).Take(20).Print();
        TurnWheels(('A', "1B2"), ('B', "34")).Take(20).Print();
        TurnWheels(('A', "1DD"), ('D', "678")).Take(20).Print();
        TurnWheels(('A', "1BC"), ('B', "34"), ('C', "5B")).Take(20).Print();
    }

    static IEnumerable<char> TurnWheels(params (char name, string values)[] wheels) {
        var data = wheels.ToDictionary(wheel => wheel.name, wheel => wheel.values.Loop().GetEnumerator());
        var primary = data[wheels[0].name];
        while (true) {
            yield return Turn(primary);
        }

        char Turn(IEnumerator<char> sequence) {
            sequence.MoveNext();
            char c = sequence.Current;
            return char.IsDigit(c) ? c : Turn(data[c]);
        }
    }

    static IEnumerable<T> Loop<T>(this IEnumerable<T> seq) {
        while (true) {
            foreach (T element in seq) yield return element;
        }
    }

    static void Print(this IEnumerable<char> sequence) => Console.WriteLine(string.Join(" ", sequence));
}





Python: from itertools import islice

class INW():
    

    def __init__(self, **wheels):
        self._wheels = wheels
        self.isect = {name: self._wstate(name, wheel) 
                      for name, wheel in wheels.items()}
    
    def _wstate(self, name, wheel):
        "Wheel state holder"
        assert all(val in self._wheels for val in wheel if type(val) == str), \
               f"ERROR: Interconnected wheel not found in {name}: {wheel}"
        pos = 0
        ln = len(wheel)
        while True:
            nxt, pos = wheel[pos % ln], pos + 1
            yield next(self.isect[nxt]) if type(nxt) == str else nxt
                
    def __iter__(self):
        base_wheel_name = next(self.isect.__iter__())
        yield from self.isect[base_wheel_name]
        
    def __repr__(self):
        return f"{self.__class__.__name__}({self._wheels})"
    
    def __str__(self):
        txt = "Intersecting Number Wheel group:"
        for name, wheel in self._wheels.items():
            txt += f"\n  {name+':':4}" + ' '.join(str(v) for v in wheel)
        return txt

def first(iter, n):
    "Pretty print first few terms"
    return ' '.join(f"{nxt}" for nxt in islice(iter, n))

if __name__ == '__main__':
    for group in[
      {'A': (1, 2, 3)},
      {'A': (1, 'B', 2),
       'B': (3, 4)},
      {'A': (1, 'D', 'D'),
       'D': (6, 7, 8)},
      {'A': (1, 'B', 'C'),
       'B': (3, 4),
       'C': (5, 'B')}, 
     ]:
        w = INW(**group)
        print(f"{w}\n  Generates:\n    {first(w, 20)} ...\n")
Task: Time a function

C: #include <stdio.h>
#include <time.h>

int identity(int x) { return x; }

int sum(int s)
{
  int i;
  for(i=0; i < 1000000; i++) s += i;
  return s;
}

#ifdef CLOCK_PROCESS_CPUTIME_ID

#define CLOCKTYPE  CLOCK_PROCESS_CPUTIME_ID
#else

#define CLOCKTYPE  CLOCK_MONOTONIC
#endif

double time_it(int (*action)(int), int arg)
{
  struct timespec tsi, tsf;

  clock_gettime(CLOCKTYPE, &tsi);
  action(arg);
  clock_gettime(CLOCKTYPE, &tsf);

  double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
  long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
  return elaps_s + ((double)elaps_ns) / 1.0e9;
}

int main()
{
  printf("identity (4) takes %lf s\n", time_it(identity, 4));
  printf("sum      (4) takes %lf s\n", time_it(sum, 4));
  return 0;
}



C#: using System;
using System.Linq;
using System.Threading;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        Stopwatch sw = new Stopwatch();

        sw.Start();
        DoSomething();
        sw.Stop();

        Console.WriteLine("DoSomething() took {0}ms.", sw.Elapsed.TotalMilliseconds);
    }

    static void DoSomething() {
        Thread.Sleep(1000);

        Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum();  
    }
}
Task: Time a function

C: #include <stdio.h>
#include <time.h>

int identity(int x) { return x; }

int sum(int s)
{
  int i;
  for(i=0; i < 1000000; i++) s += i;
  return s;
}

#ifdef CLOCK_PROCESS_CPUTIME_ID

#define CLOCKTYPE  CLOCK_PROCESS_CPUTIME_ID
#else

#define CLOCKTYPE  CLOCK_MONOTONIC
#endif

double time_it(int (*action)(int), int arg)
{
  struct timespec tsi, tsf;

  clock_gettime(CLOCKTYPE, &tsi);
  action(arg);
  clock_gettime(CLOCKTYPE, &tsf);

  double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
  long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
  return elaps_s + ((double)elaps_ns) / 1.0e9;
}

int main()
{
  printf("identity (4) takes %lf s\n", time_it(identity, 4));
  printf("sum      (4) takes %lf s\n", time_it(sum, 4));
  return 0;
}


C++: #include <ctime>
#include <iostream>
using namespace std;

int identity(int x) { return x; }
int sum(int num) {
  for (int i = 0; i < 1000000; i++)
    num += i;
  return num;
}

double time_it(int (*action)(int), int arg) {
  clock_t start_time = clock();
  action(arg);
  clock_t finis_time = clock();
  return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}

int main() {
  cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
  cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
  return 0;
}
Task: Time a function

C: #include <stdio.h>
#include <time.h>

int identity(int x) { return x; }

int sum(int s)
{
  int i;
  for(i=0; i < 1000000; i++) s += i;
  return s;
}

#ifdef CLOCK_PROCESS_CPUTIME_ID

#define CLOCKTYPE  CLOCK_PROCESS_CPUTIME_ID
#else

#define CLOCKTYPE  CLOCK_MONOTONIC
#endif

double time_it(int (*action)(int), int arg)
{
  struct timespec tsi, tsf;

  clock_gettime(CLOCKTYPE, &tsi);
  action(arg);
  clock_gettime(CLOCKTYPE, &tsf);

  double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
  long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
  return elaps_s + ((double)elaps_ns) / 1.0e9;
}

int main()
{
  printf("identity (4) takes %lf s\n", time_it(identity, 4));
  printf("sum      (4) takes %lf s\n", time_it(sum, 4));
  return 0;
}





Java: import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class TimeIt {
	public static void main(String[] args) {
		final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
		assert threadMX.isCurrentThreadCpuTimeSupported();
		threadMX.setThreadCpuTimeEnabled(true);
		
		long start, end;
		start = threadMX.getCurrentThreadCpuTime();
		countTo(100000000);
		end = threadMX.getCurrentThreadCpuTime();
		System.out.println("Counting to 100000000 takes "+(end-start)/1000000+"ms");
		start = threadMX.getCurrentThreadCpuTime();
		countTo(1000000000L);
		end = threadMX.getCurrentThreadCpuTime();
		System.out.println("Counting to 1000000000 takes "+(end-start)/1000000+"ms");
 
	}
 
	public static void countTo(long x){
		System.out.println("Counting...");
		for(long i=0;i<x;i++);
		System.out.println("Done!");
	}
}
Task: Time a function

C: #include <stdio.h>
#include <time.h>

int identity(int x) { return x; }

int sum(int s)
{
  int i;
  for(i=0; i < 1000000; i++) s += i;
  return s;
}

#ifdef CLOCK_PROCESS_CPUTIME_ID

#define CLOCKTYPE  CLOCK_PROCESS_CPUTIME_ID
#else

#define CLOCKTYPE  CLOCK_MONOTONIC
#endif

double time_it(int (*action)(int), int arg)
{
  struct timespec tsi, tsf;

  clock_gettime(CLOCKTYPE, &tsi);
  action(arg);
  clock_gettime(CLOCKTYPE, &tsf);

  double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
  long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
  return elaps_s + ((double)elaps_ns) / 1.0e9;
}

int main()
{
  printf("identity (4) takes %lf s\n", time_it(identity, 4));
  printf("sum      (4) takes %lf s\n", time_it(sum, 4));
  return 0;
}







Python: import sys, timeit
def usec(function, arguments):
    modname, funcname = __name__, function.__name__
    timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(),
                         setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars())
    try:
        t, N = 0, 1
        while t < 0.2:            
            t = min(timer.repeat(repeat=3, number=N))            
            N *= 10
        microseconds = round(10000000 * t / N, 1) 
        return microseconds 
    except:
        timer.print_exc(file=sys.stderr)
        raise

from math import pow
def nothing(): pass
def identity(x): return x
Task: Time a function

C: #include <stdio.h>
#include <time.h>

int identity(int x) { return x; }

int sum(int s)
{
  int i;
  for(i=0; i < 1000000; i++) s += i;
  return s;
}

#ifdef CLOCK_PROCESS_CPUTIME_ID

#define CLOCKTYPE  CLOCK_PROCESS_CPUTIME_ID
#else

#define CLOCKTYPE  CLOCK_MONOTONIC
#endif

double time_it(int (*action)(int), int arg)
{
  struct timespec tsi, tsf;

  clock_gettime(CLOCKTYPE, &tsi);
  action(arg);
  clock_gettime(CLOCKTYPE, &tsf);

  double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec);
  long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
  return elaps_s + ((double)elaps_ns) / 1.0e9;
}

int main()
{
  printf("identity (4) takes %lf s\n", time_it(identity, 4));
  printf("sum      (4) takes %lf s\n", time_it(sum, 4));
  return 0;
}








VB: Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function identity(x As Long) As Long
    For j = 0 To 1000
    identity = x
    Next j
End Function
Private Function sum(ByVal num As Long) As Long
    Dim t As Long
    For j = 0 To 1000
    t = num
    For i = 0 To 10000
        t = t + i
    Next i
    Next j
    sum = t
End Function
Private Sub time_it()
    Dim start_time As Long, finis_time As Long
    start_time = GetTickCount
    identity 1
    finis_time = GetTickCount
    Debug.Print "1000 times Identity(1) takes "; (finis_time - start_time); " milliseconds"
    start_time = GetTickCount
    sum 1
    finis_time = GetTickCount
    Debug.Print "1000 times Sum(1) takes "; (finis_time - start_time); " milliseconds"
End Sub
Task: Time a function


C++: #include <ctime>
#include <iostream>
using namespace std;

int identity(int x) { return x; }
int sum(int num) {
  for (int i = 0; i < 1000000; i++)
    num += i;
  return num;
}

double time_it(int (*action)(int), int arg) {
  clock_t start_time = clock();
  action(arg);
  clock_t finis_time = clock();
  return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}

int main() {
  cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
  cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
  return 0;
}



Go: package empty

func Empty() {}

func Count() {
    
    for i := 0; i < 1e6; i++ {
    }
}
Task: Time a function


C++: #include <ctime>
#include <iostream>
using namespace std;

int identity(int x) { return x; }
int sum(int num) {
  for (int i = 0; i < 1000000; i++)
    num += i;
  return num;
}

double time_it(int (*action)(int), int arg) {
  clock_t start_time = clock();
  action(arg);
  clock_t finis_time = clock();
  return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}

int main() {
  cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
  cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
  return 0;
}






Python: import sys, timeit
def usec(function, arguments):
    modname, funcname = __name__, function.__name__
    timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(),
                         setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars())
    try:
        t, N = 0, 1
        while t < 0.2:            
            t = min(timer.repeat(repeat=3, number=N))            
            N *= 10
        microseconds = round(10000000 * t / N, 1) 
        return microseconds 
    except:
        timer.print_exc(file=sys.stderr)
        raise

from math import pow
def nothing(): pass
def identity(x): return x
Task: Time a function


C++: #include <ctime>
#include <iostream>
using namespace std;

int identity(int x) { return x; }
int sum(int num) {
  for (int i = 0; i < 1000000; i++)
    num += i;
  return num;
}

double time_it(int (*action)(int), int arg) {
  clock_t start_time = clock();
  action(arg);
  clock_t finis_time = clock();
  return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC;
}

int main() {
  cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl;
  cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl;
  return 0;
}







VB: Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function identity(x As Long) As Long
    For j = 0 To 1000
    identity = x
    Next j
End Function
Private Function sum(ByVal num As Long) As Long
    Dim t As Long
    For j = 0 To 1000
    t = num
    For i = 0 To 10000
        t = t + i
    Next i
    Next j
    sum = t
End Function
Private Sub time_it()
    Dim start_time As Long, finis_time As Long
    start_time = GetTickCount
    identity 1
    finis_time = GetTickCount
    Debug.Print "1000 times Identity(1) takes "; (finis_time - start_time); " milliseconds"
    start_time = GetTickCount
    sum 1
    finis_time = GetTickCount
    Debug.Print "1000 times Sum(1) takes "; (finis_time - start_time); " milliseconds"
End Sub
Task: Time a function



C#: using System;
using System.Linq;
using System.Threading;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        Stopwatch sw = new Stopwatch();

        sw.Start();
        DoSomething();
        sw.Stop();

        Console.WriteLine("DoSomething() took {0}ms.", sw.Elapsed.TotalMilliseconds);
    }

    static void DoSomething() {
        Thread.Sleep(1000);

        Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum();  
    }
}


Go: package empty

func Empty() {}

func Count() {
    
    for i := 0; i < 1e6; i++ {
    }
}
Task: Time a function



C#: using System;
using System.Linq;
using System.Threading;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        Stopwatch sw = new Stopwatch();

        sw.Start();
        DoSomething();
        sw.Stop();

        Console.WriteLine("DoSomething() took {0}ms.", sw.Elapsed.TotalMilliseconds);
    }

    static void DoSomething() {
        Thread.Sleep(1000);

        Enumerable.Range(1, 10000).Where(x => x % 2 == 0).Sum();  
    }
}



Java: import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class TimeIt {
	public static void main(String[] args) {
		final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
		assert threadMX.isCurrentThreadCpuTimeSupported();
		threadMX.setThreadCpuTimeEnabled(true);
		
		long start, end;
		start = threadMX.getCurrentThreadCpuTime();
		countTo(100000000);
		end = threadMX.getCurrentThreadCpuTime();
		System.out.println("Counting to 100000000 takes "+(end-start)/1000000+"ms");
		start = threadMX.getCurrentThreadCpuTime();
		countTo(1000000000L);
		end = threadMX.getCurrentThreadCpuTime();
		System.out.println("Counting to 1000000000 takes "+(end-start)/1000000+"ms");
 
	}
 
	public static void countTo(long x){
		System.out.println("Counting...");
		for(long i=0;i<x;i++);
		System.out.println("Done!");
	}
}