Showing posts with label macro. Show all posts
Showing posts with label macro. Show all posts

Thursday, June 14, 2012

To calculate SAS program run time

Sometimes, I wanted to compare the efficiency between two approaches. I used following codes to get the program execution run-time:
 
%let _sdtm=%sysfunc(datetime());
*** SAS codes ***;
%let _edtm=%sysfunc(datetime());
%let _runtm=%sysfunc(putn(&_edtm - &_sdtm, 12.4));
%put It took &_runtm second to run the program;

It is also very easy to print the date and time:
%put %sysfunc(putn(&_sdtm, datetime20.));

Friday, June 1, 2012

To get obs number of a dataset


There are some approaches to get observation number of a dataset.

I usually use the observation numbers to decide how to generate a TLG. For example, if there is no data, I would generate a table with text as “No observation found…”, instead of no output or a blank page.

Mostly, I would use following codes:
%LET dsid =%sysfunc(OPEN(dataset_name));
%LET nobs =%sysfunc(ATTRN(&dsid, NLOBS));
%LET rc =%sysfunc(CLOSE(&dsid));
It should be good enough for me, because I know the dataset will be there. This means, above codes will not work for SAS views or if a dataset does not exist. If I want to put above codes in more general programs, I may check &dsid if the dataset exists.

I can also use SASHELP.VTABLE to fetch dataset information I want. It usually consumes a little more brain energy to get there, for example, I have to deal more details on libname and memname, and maybe more keystrokes.

If I want to know the observation numbers of subset of a dataset, which means a dataset with WHERE statement, it seems that I have to count the observations one by one. Usually, I use following codes:
%LET nobs=0;
DATA _null_;
    SET dataset_name (WHERE=(where_statement)) end=eof;
    IF eof THEN CALL SYMPUTX("nobs",_n_);
RUN;

It is important to have "%let nobs=0;" to initiate macro variable nobs.

Thursday, May 10, 2012

A macro variable with "current date" in yymmdd10. format

You may already know that SAS system provides two automatic macro variables, &sysdate and &sysdate9, to contain the date that a SAS job or session began executing. Mot of the time, these two macro variables are good enough to be treated as current date. 

The issue I had is that these dates are in Date7. and Date9. format. I usually want to create folder/file names with dates in YYYY-MM-DD format, so that those folders/files could be sorted correctly. 

Here I present a simple way to create a macro variable &cdate with re-formatting &sysdate9 to YYYY-MM-DD format.

%let cdate=%sysfunc(putn("&sysdate9"d,yymmdd10.));
%put &cdate;

** Updated on 2012-06-05 **;
** If using today's date, instead of &sysdate or &sysdate9, Here is the codes **;
%let cdate=%sysfunc(date(),yymmdd10.);
%put &cdate;