`
dasheng
  • 浏览: 145903 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Sort源代码注释

阅读更多
package org.apache.hadoop.examples;

import java.io.IOException;
import java.net.URI;
import java.util.*;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.mapred.lib.IdentityMapper;
import org.apache.hadoop.mapred.lib.IdentityReducer;
import org.apache.hadoop.mapred.lib.InputSampler;
import org.apache.hadoop.mapred.lib.TotalOrderPartitioner;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 hadoop 的map/reduce例子,排序,由于map传给reduce的中间结果是排序的,所以这个例子不用写mapper和reducer。都用默认的map/reduce的实现,
IdentityMapper和IdentityReducer。例子中可以用排序采样器TotalOrderPartitioner,参数设置可以是 -totalOrder 0.1 10000 10
 * This is the trivial map/reduce program that does absolutely nothing
 * other than use the framework to fragment and sort the input values.
 *
 * To run: bin/hadoop jar build/hadoop-examples.jar sort
 *            [-m <i>maps</i>] [-r <i>reduces</i>]
 *            [-inFormat <i>input format class</i>] 
 *            [-outFormat <i>output format class</i>] 
 *            [-outKey <i>output key class</i>] 
 *            [-outValue <i>output value class</i>] 
 *            [-totalOrder <i>pcnt</i> <i>num samples</i> <i>max splits</i>]
 *            <i>in-dir</i> <i>out-dir</i> 
 */
public class Sort<K,V> extends Configured implements Tool {
  private RunningJob jobResult = null;

  static int printUsage() {
    System.out.println("sort [-m <maps>] [-r <reduces>] " +
                       "[-inFormat <input format class>] " +
                       "[-outFormat <output format class>] " + 
                       "[-outKey <output key class>] " +
                       "[-outValue <output value class>] " +
                       "[-totalOrder <pcnt> <num samples> <max splits>] " +
                       "<input> <output>");
    ToolRunner.printGenericCommandUsage(System.out);
    return -1;
  }

  /**driver代码
   * The main driver for sort program.
   * Invoke this method to submit the map/reduce job.
   * @throws IOException When there is communication problems with the 
   *                     job tracker.
   */
  public int run(String[] args) throws Exception {

    JobConf jobConf = new JobConf(getConf(), Sort.class);
    jobConf.setJobName("sorter");

    jobConf.setMapperClass(IdentityMapper.class);  //设置mapper      
    jobConf.setReducerClass(IdentityReducer.class);//设置reducer

    JobClient client = new JobClient(jobConf);
    ClusterStatus cluster = client.getClusterStatus();//获得集群的状态
    int num_reduces = (int) (cluster.getMaxReduceTasks() * 0.9);
    String sort_reduces = jobConf.get("test.sort.reduces_per_host");
    if (sort_reduces != null) {
       num_reduces = cluster.getTaskTrackers() * 
                       Integer.parseInt(sort_reduces);
    }
    Class<? extends InputFormat> inputFormatClass = 
      SequenceFileInputFormat.class;
    Class<? extends OutputFormat> outputFormatClass = 
      SequenceFileOutputFormat.class;
    Class<? extends WritableComparable> outputKeyClass = BytesWritable.class;
    Class<? extends Writable> outputValueClass = BytesWritable.class;
    List<String> otherArgs = new ArrayList<String>();
    InputSampler.Sampler<K,V> sampler = null;
    for(int i=0; i < args.length; ++i) {
      try {
        if ("-m".equals(args[i])) {
          jobConf.setNumMapTasks(Integer.parseInt(args[++i]));
        } else if ("-r".equals(args[i])) {
          num_reduces = Integer.parseInt(args[++i]);
        } else if ("-inFormat".equals(args[i])) {
          inputFormatClass = 
            Class.forName(args[++i]).asSubclass(InputFormat.class);
        } else if ("-outFormat".equals(args[i])) {
          outputFormatClass = 
            Class.forName(args[++i]).asSubclass(OutputFormat.class);
        } else if ("-outKey".equals(args[i])) {
          outputKeyClass = 
            Class.forName(args[++i]).asSubclass(WritableComparable.class);
        } else if ("-outValue".equals(args[i])) {
          outputValueClass = 
            Class.forName(args[++i]).asSubclass(Writable.class);
        } else if ("-totalOrder".equals(args[i])) { //设置采样器3个参数
          double pcnt = Double.parseDouble(args[++i]);
          int numSamples = Integer.parseInt(args[++i]);
          int maxSplits = Integer.parseInt(args[++i]);
          if (0 >= maxSplits) maxSplits = Integer.MAX_VALUE;
          sampler =
            new InputSampler.RandomSampler<K,V>(pcnt, numSamples, maxSplits);
        } else {
          otherArgs.add(args[i]);
        }
      } catch (NumberFormatException except) {
        System.out.println("ERROR: Integer expected instead of " + args[i]);
        return printUsage();
      } catch (ArrayIndexOutOfBoundsException except) {
        System.out.println("ERROR: Required parameter missing from " +
            args[i-1]);
        return printUsage(); // exits
      }
    }

    // Set user-supplied (possibly default) job configs
    jobConf.setNumReduceTasks(num_reduces);

    jobConf.setInputFormat(inputFormatClass);
    jobConf.setOutputFormat(outputFormatClass);

    jobConf.setOutputKeyClass(outputKeyClass);
    jobConf.setOutputValueClass(outputValueClass);

    // Make sure there are exactly 2 parameters left.
    if (otherArgs.size() != 2) {
      System.out.println("ERROR: Wrong number of parameters: " +
          otherArgs.size() + " instead of 2.");
      return printUsage();
    }
    FileInputFormat.setInputPaths(jobConf, otherArgs.get(0));
    FileOutputFormat.setOutputPath(jobConf, new Path(otherArgs.get(1)));

    if (sampler != null) {
      System.out.println("Sampling input to effect total-order sort...");
      jobConf.setPartitionerClass(TotalOrderPartitioner.class);//设置采样器
      Path inputDir = FileInputFormat.getInputPaths(jobConf)[0];
      inputDir = inputDir.makeQualified(inputDir.getFileSystem(jobConf));
      Path partitionFile = new Path(inputDir, "_sortPartitioning");
      TotalOrderPartitioner.setPartitionFile(jobConf, partitionFile);//采样设置采样文件
      InputSampler.<K,V>writePartitionFile(jobConf, sampler);
      URI partitionUri = new URI(partitionFile.toString() +
                                 "#" + "_sortPartitioning");
      DistributedCache.addCacheFile(partitionUri, jobConf);
      DistributedCache.createSymlink(jobConf);
    }

    System.out.println("Running on " +
        cluster.getTaskTrackers() +
        " nodes to sort from " + 
        FileInputFormat.getInputPaths(jobConf)[0] + " into " +
        FileOutputFormat.getOutputPath(jobConf) +
        " with " + num_reduces + " reduces.");
    Date startTime = new Date();
    System.out.println("Job started: " + startTime);
    jobResult = JobClient.runJob(jobConf);
    Date end_time = new Date();
    System.out.println("Job ended: " + end_time);
    System.out.println("The job took " + 
        (end_time.getTime() - startTime.getTime()) /1000 + " seconds.");
    return 0;
  }



  public static void main(String[] args) throws Exception {
    int res = ToolRunner.run(new Configuration(), new Sort(), args);
    System.exit(res);
  }

  /**
   * Get the last job that was run using this instance.
   * @return the results of the last job that was run
   */
  public RunningJob getResult() {
    return jobResult;
  }
}
 
分享到:
评论

相关推荐

    数据结构与算法全集(C源代码+详细注释)

    │ │ TopologicalSort.cpp │ │ TopologicalSort.h │ │ VertexType.cpp │ │ VertexType.h │ │ │ ├─插入排序 │ │ 1.txt │ │ main.cpp │ │ RedType.cpp │ │ RedType.h │ │ Sq_InsertSort.cpp │ ...

    C语言课程设计——学生成绩管理系统(源代码+详细注释).zip

    case 7:Sort(l);break; /*排序学生记录*/ case 8:Save(l);break; /*保存学生记录*/ case 9:system("cls");Disp(l);break; /*显示学生记录*/ default: Wrong();getchar();break; /*按键有误,必须为数值0-9*/ }...

    numpy数据分析源代码+大数据的读取_.ipynb

    详细的,有解释的源代码哦 pandas数据处理 1、删除重复元素 使用duplicated()函数检测重复的行,返回元素为布尔类型的Series对象,每个元素对应一行,如果该行不是第一次出现,则元素为True df.duplicated() ...

    VB指针葵花宝典之函数指针的配套代码。

    其中ShellSort完全是取自1998年5月VBPJ的Black Belt专栏里的源代码,可以说本文的思想基本上也来自这篇专栏文章。 ShellSort提共了三种不同的实现方法,分别是如下: PolySort1: 用Variant和对象缺省属性来比较...

    sc-Deepsort-Reproduce:Repdocue scDeepsort

    scDeepSort 使用加权图神经网络进行深度学习的单细胞转录组学无参考细胞类型注释 单细胞RNA测序(scRNA-seq)的最新进展已使大规模复杂组织中数千个细胞的大规模转录表征成为可能...下载scDeepSort的源代码。 从下载经

    bash-sort:bash中基本排序算法的实现

    Smith,aka kojiro, 上次修改时间:2009-10-10用法和注释:您只需提供文件源即可访问脚本中的功能。 如果要测试某些功能,请使用./sort.bash -t funclist 该代码在MIT许可下按原样发布。 可以在上找到MIT许可证,...

    数据结构和算法:用Java实现的抽象数据结构的集合

    该代码经过了很好的注释,可以轻松理解。 每个数据结构都经过良好测试。 您可以通过与我联系。 数据结构 : 此仓库包含以下数据结构: 排序算法 图上的算法 图表示 我们有以下三个图形表示: 图中的算法 到达:...

    Python字典排序与取值

    源代码 每一行都写注释了,就不分析什么鬼了 #定义一个 find_max_and_min 函数 def find_max_and_min(stock_dict): # 对传入的字典根据value排序(升序) dict_sort=sorted(stock_dict.items(),key=lambda item:item...

    go-cshared-examples:使用C共享库从其他语言调用Go函数

    以下Go源代码导出了四个函数Add , Cosine , Sort和Log 。 诚然,很棒的库没有那么令人印象深刻。 但是,其多样的功能签名将帮助我们探索类型映射的含义。 档案 package mainimport "C"import ("fmt

    Java实现排序和递归算法示例

    自己写的4个Java代码,内有详细注释,适合想学Java的朋友参考。 insertion_sort.java --插入排序 Divide.java --分治排序 HanoiCompute.java --递归实现汉诺塔 FileCtrl.java --递归实现显示目录下的...

    数据结构课程设计--排序算法性能分析

    6. 源程序(带注释) 16 总 结 28 参考文献 29 致 谢 30 附件Ⅰ 部分源程序代码 31 摘要 排序是计算机程序设计中的一种重要操作。各种部排序算法的时间复杂度分析结果只给出了算法执行时间的阶,或大概执行时间。...

    PHP和MySQL Web开发第4版pdf以及源码

    1.3.4 注释 1.4 添加动态内容 1.4.1 调用函数 1.4.2 使用date()函数 1.5 访问表单变量 1.5.1 简短、中等以及长风格的表单变量 1.5.2 字符串的连接 1.5.3 变量和文本 1.6 理解标识符 1.7 检查变量类型 ...

    PHP和MySQL WEB开发(第4版)

    1.3.4 注释 1.4 添加动态内容 1.4.1 调用函数 1.4.2 使用date()函数 1.5 访问表单变量 1.5.1 简短、中等以及长风格的表单变量 1.5.2 字符串的连接 1.5.3 变量和文本 1.6 理解标识符 1.7 检查变量类型 1.7.1 PHP的...

    PHP和MySQL Web开发第4版

    1.3.4 注释 1.4 添加动态内容 1.4.1 调用函数 1.4.2 使用date()函数 1.5 访问表单变量 1.5.1 简短、中等以及长风格的表单变量 1.5.2 字符串的连接 1.5.3 变量和文本 1.6 理解标识符 1.7 检查变量类型 ...

    PHP基础教程 是一个比较有价值的PHP新手教程!

    在许多人的无私奉献下以及这种语言本身的源代码自由性质,它演变成为一种特点丰富的语言,而且现在还在成长中。 PHP虽然很容易学习,但是速度上比mod_perl(植入web服务器的perl模块)慢。现在有了可以与mod_perl...

    C#开发实例大全(基础卷).软件开发技术联盟(带详细书签) PDF 下载

    《C#开发实例大全(基础卷)》筛选、汇集了C#开发从基础知识到高级应用各个层面约600个实例及源代码,每个实例都按实例说明、关键技术、设计过程、详尽注释、秘笈心法的顺序进行了分析解读。全书分6篇共25章,主要...

    C语言课程设计运动会成绩管理系统.doc

    代码应适当缩进,并给出必要的注释,以增强程序的可读性。 2. 课程设计说明书: 课程结束后,上交课程设计说明书和源程序。课程设计说明书的格式和内容参见 提供的模板。 四、指导教师和学生签字 指导教师:_______...

    【。net 专业】 面试题

    3.datagrid.datasouse可以连接什么数据源 [dataset,datatable,dataview] dataset,datatable,dataview , IList 4.概述反射和序列化 反射:程序集包含模块,而模块包含类型,类型又包含成员。反射则提供了封装程序集、...

Global site tag (gtag.js) - Google Analytics